import os
import re

from Oa_system.models import Staffing
from administrative.models import *
from django.shortcuts import render, HttpResponse, redirect
from system_setup.models import *
from finance.models import *
from announcements.models import *
from forum.views import str_to_timestamp
from logistics.models import *
from personal_center.models import *
from back_management.models import *
from supervision_inspection.models import *
from datetime import datetime, timedelta, date
from django.db import connection
from django.db.models import Q
from django.views import View
import json, time, xlrd, random, base64, urllib.parse
from administrative.utils import send_mssage




# 获取本周一的日期
def this_monday(today):
    """
    :function: 获取本周周一日期
    :param today:
    :return: 返回周一的日期
    :return_type: string
    """
    today = datetime.strptime(str(today), "%Y-%m-%d")
    return datetime.strftime(today - timedelta(today.weekday()), "%Y-%m-%d")

class login(View):
    def get(self, request):
        return render(request, "back_management/login.html")

class index(View):
    def get(self, request):
        try:
            request.user.real_name
        except Exception as E:
            return redirect("/")
        return render(request, "back_management/index.html")

class welcome(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        select_sql = "SELECT B.department dep, COUNT(*) counts FROM administrative_topics A LEFT JOIN tb_users_message B ON A.employee_id=B.id GROUP BY dep ORDER BY counts DESC"
        with connection.cursor() as cursor:
            cursor.execute(select_sql)
            rows1 = cursor.fetchall()
        def_list = [{"dep": i[0], "count": i[1]} for i in rows1]

        # 总数
        MemoCount = ConferenceMemo.objects.filter(state__in=['nine', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']).count()
        OfficialCount = OfficialDocuments.objects.filter(state__in=["a", "b", "c", "d", "e", "f", "g", "h"]).count()
        TopiCount = Topics.objects.filter(state__in=["draft", "confirm", "audit", "done", "refuse", "sj"]).count()
        TopicsattachmentsCount = Topicsattachments.objects.all().count()
        UserCount = User.objects.filter(~Q(real_name='管理员'), is_delete=0).count()

        # 今日数据
        today_start_time = f'{time.strftime("%Y-%m-%d", time.localtime())} 00:00:00'
        today_end_time = f'{time.strftime("%Y-%m-%d", time.localtime())} 23:59:59'
        TodayMemoCount = ConferenceMemo.objects.filter(state__in=['nine', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'], create_time__range=[today_start_time, today_end_time]).count()
        TodayTopiCount = Topics.objects.filter(state__in=["draft", "confirm", "audit", "done", "refuse", "sj"], create_time__range=[today_start_time, today_end_time]).count()
        TodayTopicsattachmentsCount = Topicsattachments.objects.filter(create_time__range=[today_start_time, today_end_time]).count()
        TodayUserCount = User.objects.filter(~Q(real_name='管理员'), is_delete=0, create_time__range=[today_start_time, today_end_time]).count()
        TodayOfficialCount = OfficialDocuments.objects.filter(state__in=["a", "b", "c", "d", "e", "f", "g", "h"], create_time__range=[today_start_time, today_end_time]).count()

        # 昨日数据
        yesterday = (date.today() + timedelta(days=-1)).strftime("%Y-%m-%d")
        yesterday_start_time = f'{yesterday} 00:00:00'
        yesterday_end_time = f'{yesterday} 23:59:59'
        YesterdayMemoCount = ConferenceMemo.objects.filter(state__in=['nine', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'], create_time__range=[yesterday_start_time, yesterday_end_time]).count()
        YesterdayTopiCount = Topics.objects.filter(state__in=["draft", "confirm", "audit", "done", "refuse", "sj"], create_time__range=[yesterday_start_time, yesterday_end_time]).count()
        YesterdayTopicsattachmentsCount = Topicsattachments.objects.filter(create_time__range=[yesterday_start_time, yesterday_end_time]).count()
        YesterdayUserCount = User.objects.filter(~Q(real_name='管理员'), is_delete=0, create_time__range=[yesterday_start_time, yesterday_end_time]).count()
        YesterdayOfficialCount = OfficialDocuments.objects.filter(state__in=["a", "b", "c", "d", "e", "f", "g", "h"], create_time__range=[yesterday_start_time, yesterday_end_time]).count()

        # 本周数据
        today = f'{time.strftime("%Y-%m-%d", time.localtime())} 23:59:59'
        monday = f'{this_monday(time.strftime("%Y-%m-%d", time.localtime()))} 00:00:00'
        WeekMemoCount = ConferenceMemo.objects.filter(state__in=['nine', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'], create_time__range=[monday, today]).count()
        WeekTopiCount = Topics.objects.filter(state__in=["draft", "confirm", "audit", "done", "refuse", "sj"], create_time__range=[monday, today]).count()
        WeekTopicsattachmentsCount = Topicsattachments.objects.filter(create_time__range=[monday, today]).count()
        WeekUserCount = User.objects.filter(~Q(real_name='管理员'), is_delete=0, create_time__range=[monday, today]).count()
        WeekOfficialCount = OfficialDocuments.objects.filter(state__in=["a", "b", "c", "d", "e", "f", "g", "h"], create_time__range=[monday, today]).count()

        # 本月数据
        now = datetime.now()
        this_month_start = datetime(now.year, now.month, 1)
        MonthMemoCount = ConferenceMemo.objects.filter(state__in=['nine', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'], create_time__range=[this_month_start, today]).count()
        MonthTopiCount = Topics.objects.filter(state__in=["draft", "confirm", "audit", "done", "refuse", "sj"], create_time__range=[this_month_start, today]).count()
        MonthTopicsattachmentsCount = Topicsattachments.objects.filter(create_time__range=[this_month_start, today]).count()
        MonthUserCount = User.objects.filter(~Q(real_name='管理员'), is_delete=0, create_time__range=[this_month_start, today]).count()
        MonthOfficialCount = OfficialDocuments.objects.filter(state__in=["a", "b", "c", "d", "e", "f", "g", "h"], create_time__range=[this_month_start, today]).count()
        all_data_list = [
            {"alldata": "总数", "AllMemoCount": MemoCount, "OfficialCount": OfficialCount, "AllTopiCount": TopiCount, "AllMentsCount": TopicsattachmentsCount, "AllUserCount": UserCount},
            {"alldata": "今日", "AllMemoCount": TodayMemoCount, "OfficialCount": TodayOfficialCount, "AllTopiCount": TodayTopiCount, "AllMentsCount": TodayTopicsattachmentsCount, "AllUserCount": TodayUserCount},
            {"alldata": "昨日", "AllMemoCount": YesterdayMemoCount, "OfficialCount": YesterdayOfficialCount, "AllTopiCount": YesterdayTopiCount, "AllMentsCount": YesterdayTopicsattachmentsCount, "AllUserCount": YesterdayUserCount},
            {"alldata": "本周", "AllMemoCount": WeekMemoCount, "OfficialCount": WeekOfficialCount, "AllTopiCount": WeekTopiCount, "AllMentsCount": WeekTopicsattachmentsCount, "AllUserCount": WeekUserCount},
            {"alldata": "本月", "AllMemoCount": MonthMemoCount, "OfficialCount": MonthOfficialCount, "AllTopiCount": MonthTopiCount, "AllMentsCount": MonthTopicsattachmentsCount, "AllUserCount": MonthUserCount}
        ]

        return render(request, "back_management/welcome.html", {"def_list": def_list, "all_data_list": all_data_list})

# 院长办公会议题列表
class TopicsOfficeMeeting(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/TopicsOfficeMeeting.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", "")  # 查询标题
        objs = Topics.objects.filter(Q(number__contains=search_data) |
                                     Q(topics_name__contains=search_data) |
                                     Q(employee__real_name__contains=search_data) |
                                     Q(employee__company__name__contains=search_data), type='yb', state__in=["draft", "confirm", "audit", "yd_leader", "db_leader", "done", "refuse", "sj", "unmetting", "metting", "shelve", "OPR", "stop"]).order_by('-create_time')
        data_list = [
            {'id': obj.id, 'title': obj.topics_name, 'apply_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'approver': obj.current_audit_user, 'topics_number': obj.number, "apply_dep": obj.employee.company.name, "apply_people": obj.employee.real_name,
             'status': obj.get_state_str1()}
            for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 议题详情
class TopicDetail(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        iss_id = request.GET.get("id", None)
        topics_obj = Topics.objects.get(id=int(iss_id))
        top_obj = Topics.objects.get(id=int(iss_id)).topicsauditrecord_set.all()
        audit_dic = {}
        for audit_obj in top_obj:
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        main_file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "pdf_path": atta_obj.pdf_path,
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=topics_obj.uuid)]
        print(main_file_list)
        help_department = ' ,'.join([i.name for i in topics_obj.help_department.all()])
        help_department1 = ' ,'.join([f"{i.name}({i.id})" for i in topics_obj.help_department.all()])
        data_dic = {'apply_user': topics_obj.employee.real_name,
                    'department': topics_obj.employee.department,
                    'state': topics_obj.get_state_display(),
                    'main_file_list': main_file_list,
                    'number': topics_obj.number,
                    'topics_name': topics_obj.topics_name,
                    'topics_text': base64.b64decode(topics_obj.topics_text).decode(),
                    'topics_basis': base64.b64decode(topics_obj.topics_basis).decode(),
                    'solution': base64.b64decode(topics_obj.solution).decode() if topics_obj.solution != "空" else "",
                    'db_topics_text': base64.b64decode(topics_obj.db_topics_text).decode() if topics_obj.db_topics_text else "",
                    'db_topics_basis': base64.b64decode(topics_obj.db_topics_basis).decode() if topics_obj.db_topics_basis else "",
                    'db_solution': base64.b64decode(topics_obj.db_solution).decode() if topics_obj.db_solution else "",
                    'topics_estimate': topics_obj.topics_estimate,
                    'help_department': help_department,
                    'help_department1': help_department1,
                    'jfly': topics_obj.jfly if topics_obj.jfly else "",
                    'ysje': topics_obj.ysje if topics_obj.ysje else "",
                    'uuid': topics_obj.uuid,
                    'audit_list': audit_dic,
                    'yb_number': Topics.objects.get(id=int(topics_obj.HouseToParty_id)).number if topics_obj.HouseToParty_id else '',
                    'is_audit': 'false',
                    'file_path': Topicsattachments.objects.filter(topics_number=topics_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=topics_obj.uuid) else ''}
        return render(request, "back_management/TopicDetail.html", {"top_obj": audit_dic, "obj": topics_obj, 'data_dic': data_dic})

    def post(self, request):
        """删除议题"""
        topic_id = request.POST.get("topic_id", None)                           # 议题ID
        topics_number = request.POST.get("topics_number", None)                 # 议题编号
        zy_number = request.POST.get("zy_number", None)                         # 是否占用编号
        print(topic_id)
        topic_obj = Topics.objects.get(id=topic_id)
        topic_obj.topicsauditrecord_set.all().delete()                                 # 清除审批列表
        topic_obj.already_users.clear()                    # 清除已审批列表
        topic_obj.help_department.clear()                  # 清除协办科室
        Topicsattachments.objects.filter(topics_number=topics_number).delete()
        topic_obj.delete()
        if topic_obj.public_search:
            topic_obj.public_search.audit_users_already.clear()
            topic_obj.public_search.current_audit_users.clear()
            topic_obj.public_search.delete()

        if zy_number == "False":
            number_list = topics_number.split('-')
            current_updata_bunber = number_list[-1]             # 当前更改的编号号码
            Sequence_obj = Sequence.objects.filter(type="-".join(number_list[:2]), topic_year=number_list[2])[0]
            next_sequence = Sequence_obj.next_sequence           # 下一个编号
            sequence = Sequence_obj.sequence                        # 当前编号

            if int(sequence) > int(current_updata_bunber):
                for i in range(int(current_updata_bunber)+1, int(next_sequence)):
                    if i < 10:
                        SeqNumber = f'0{i}'
                    else:
                        SeqNumber = i
                    Topics_list = Topics.objects.filter(number="-".join(number_list[:3])+f"-{SeqNumber}")
                    for j in Topics_list:
                        if i-1 < 10:
                            seq_number = f'0{i-1}'
                        else:
                            seq_number = i-1
                        j.number = "-".join(number_list[:3])+f"-{seq_number}"
                        j.save()

            Sequence_obj.sequence = int(sequence)-1
            Sequence_obj.next_sequence = sequence
            Sequence_obj.save()
        returnDict = {'status': 'success', 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 党委会议题列表页
class TopicsPartyMeeting(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/TopicsPartyMeeting.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", "")  # 查询标题
        objs = Topics.objects.filter(Q(number__contains=search_data) |
                                     Q(topics_name__contains=search_data) |
                                     Q(employee__real_name__contains=search_data) |
                                     Q(employee__company__name__contains=search_data), type='db',
                                     state__in=["draft", "confirm", "audit", "yd_leader", "db_leader", "sj", "done", "unmetting", "metting", "shelve", "refuse", "stop", "PG", "db_one_step", "db_two_step", "db_three_step", "db_four_step", "marks"]).order_by('-create_time')
        data_list = [
            {'id': obj.id, 'title': obj.topics_name, 'apply_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'approver': obj.current_audit_user, 'topics_number': obj.number, "apply_dep": obj.employee.company.name, "apply_people": obj.employee.real_name,
             'status': obj.get_state_str1()}
            for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 行政例会议题列表页
class TopicsRegularMeeting(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/TopicsRegularMeeting.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", "")  # 查询标题
        objs = Topics.objects.filter(Q(number__contains=search_data) |
                                     Q(topics_name__contains=search_data) |
                                     Q(employee__real_name__contains=search_data) |
                                     Q(employee__company__name__contains=search_data), type='xz', state__in=["draft", "confirm", "audit", "yd_leader", "db_leader", "sj", "done", "unmetting", "metting", "shelve", "refuse", "stop"]).order_by('-create_time')
        data_list = [
            {'id': obj.id, 'title': obj.topics_name, 'apply_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'approver': obj.current_audit_user, 'topics_number': obj.number, "apply_dep": obj.employee.company.name, "apply_people": obj.employee.real_name,
             'status': obj.get_state_str1()}
            for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 议题修改
class topics_modify_view(View):
    def post(self, request):
        id = request.POST.get('id', None)
        number = request.POST.get('number', None)  # 议题编号
        topics_name = request.POST.get('topics_name', None)  # 议题名称
        topics_text = request.POST.get('topics_text', None)  # 议题内容
        topics_basis = request.POST.get('topics_basis', None)  # 议题依据
        solution = request.POST.get('solution', "空")  # 解决方案
        ysje_str = request.POST.get('ysje', None)  # 预算金额
        jfly_str = request.POST.get('jfly', None)  # 经费来源
        topics_estimate = request.POST.get('topics_estimate', None)
        help_department1 = request.POST.get('help_department', None)
        nr_wenben = request.POST.get('nr_wenben', None)
        yj_wenben = request.POST.get('yj_wenben', None)
        fa_wenben = request.POST.get('fa_wenben', None)
        fg_people = request.POST.get('fg_people', None)  # 分管领导
        topic_type = request.POST.get('topic_type_select', '')  # 议题类型
        pay_type = request.POST.get('pay_type_select', '')  # 付款类型
        whether_outweigh = request.POST.get('whether_outweigh_20', '')  # 是否超过20万元
        Payee = request.POST.get('Payee', '')  # 收款单位
        receiving_account = request.POST.get('receiving_account', '')  # 收款账号
        opening_bank = request.POST.get('opening_bank', '')  # 开户行

        contract_type_select = request.POST.get('contract_type_select', '')  # 合同类型
        contract_name = request.POST.get('contract_name', '')  # 合同名称
        contract_number = request.POST.get('contract_number', '')  # 合同编号

        application_amount = request.POST.get('application_amount', '')  # 申请金额
        amount_words = request.POST.get('amount_words', '')  # 金额大写
        funding_source = request.POST.get('funding_source', '')  # 经费来源

        whether_bid = request.POST.get('whether_bid', '')  # 是否招标

        topics_obj = Topics.objects.get(id=int(id))
        topics_obj.topics_name = topics_name.strip()
        topics_obj.number = number
        topics_obj.pay_type = pay_type
        topics_obj.whether_outweigh = whether_outweigh
        topics_obj.topic_type = topic_type
        topics_obj.Payee = Payee
        topics_obj.whether_bid = whether_bid
        topics_obj.contract_type = contract_type_select
        topics_obj.contract_name = contract_name
        topics_obj.contract_number = contract_number
        topics_obj.receiving_account = receiving_account
        topics_obj.opening_bank = opening_bank
        topics_obj.topics_text = base64.b64encode(topics_text.encode("utf-8")).decode()
        topics_obj.topics_basis = base64.b64encode(topics_basis.encode("utf-8")).decode() if topics_basis else ''
        topics_obj.solution = base64.b64encode(solution.encode("utf-8")).decode() if solution else ''
        topics_obj.topics_estimate = topics_estimate
        topics_obj.nrwb = nr_wenben
        topics_obj.zcwb = yj_wenben if yj_wenben else ""
        topics_obj.fawb = fa_wenben if fa_wenben else ""
        topics_obj.ysje = ysje_str
        topics_obj.jfly = jfly_str
        topics_obj.application_amount = application_amount
        topics_obj.amount_words = amount_words
        topics_obj.funding_source = funding_source
        topics_obj.save()
        returnDict = {'status': 'success', "code": 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 科室管理
class DepartmentManagement(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        leaders = User.objects.filter(group_id=2)
        return render(request, "back_management/DepartmentManagement.html", {"leaders": leaders})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", "")  # 查询标题
        objs = Company.objects.filter(Q(leaders_id__real_name__contains=search_data) |                                              # 分管领导
                                      Q(name__contains=search_data) |                                                               # 科室名称
                                      Q(head_nurse_id__real_name__contains=search_data) |                                           # 护士长
                                      Q(abbreviation__contains=search_data) |                                                       # 科室简称
                                      Q(director_id__real_name__contains=search_data), ~Q(id__in=[87])).order_by('serial_number')                    # 主任

        data_list = [
            {'id': obj.id, 'name': obj.name, 'director': obj.director_id.real_name if obj.director_id else "",
             'deputy_director': ", ".join([i.real_name for i in obj.deputy_director_ids.all()]), 'head_people': obj.head_people.real_name if obj.head_people else "",
             'head_nurse': obj.head_nurse_id.real_name if obj.head_nurse_id else "", "abbreviation": obj.abbreviation,
             'leader': obj.leaders_id.real_name if obj.leaders_id else ""}
            for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 新增科室
class AddNewCompany(View):
    def post(self, request):
        company_name = request.POST.get("ks_name", None)                    # 科室名称
        director = request.POST.get("zhuren", None)                         # 主任
        deputy_director = request.POST.get("fuzhuren", None)                # 副主任
        head_nurse = request.POST.get("hsz", None)                          # 护士长
        referred = request.POST.get("ksjc", None)                           # 科室简称
        leaders = request.POST.get("fgld", None)                            # 分管领导
        functional = request.POST.get("functional", None)                   # 职能科室

        serial_number = int(Company.objects.all().order_by("-serial_number")[0].serial_number) + 1

        obj = Company.objects.create(name=company_name, abbreviation=referred, serial_number=serial_number)
        director = re.findall('\((.*?)\)', director)
        if director:
            director_obj = User.objects.filter(job_number=director[0]).first()
            if functional == "1":
                director_obj.group_id = 3
            else:
                director_obj.group_id = 4
            director_obj.company = obj
            director_obj.post = '主任'
            director_obj.department = obj.name
            director_obj.save()

            obj.director_id = director_obj
            obj.director = director_obj.real_name

        head_nurse = re.findall('\((.*?)\)', head_nurse)
        if head_nurse:
            head_nurse_obj = User.objects.filter(job_number=head_nurse[0]).first()
            head_nurse_obj.company = obj
            head_nurse_obj.post = '护士长'
            head_nurse_obj.department = obj.name
            head_nurse_obj.save()

            obj.head_nurse_id = head_nurse_obj
            obj.head_nurse = head_nurse_obj.real_name

        deputy_director = re.findall('\((.*?)\)', deputy_director)
        if deputy_director:
            for deputy_director_obj in obj.deputy_director_ids.all():
                deputy_director_obj.group_id = 6
            obj.deputy_director_ids.clear()
            deputy_director_objs = User.objects.filter(job_number__in=deputy_director)
            deputy_director_str = ', '.join([deputy_director_obj.real_name for deputy_director_obj in deputy_director_objs])
            for deputy_director_obj in deputy_director_objs:
                obj.deputy_director_ids.add(deputy_director_obj)
                deputy_director_obj.group_id = 7
                deputy_director_obj.company = obj
                deputy_director_obj.post = '副主任'
                deputy_director_obj.department = obj.name
                deputy_director_obj.save()
            obj.deputy_director = deputy_director_str

        leaders = int(leaders)
        obj.leaders_id_id = leaders
        leader_obj = User.objects.get(id=leaders)
        obj.leaders = leader_obj.real_name
        obj.leaders_id = leader_obj
        leader_obj.save()
        obj.save()
        returnDict = {'status': 'success', "code": 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 职能分组
class FunctionalGrouping(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        function_id = request.GET.get("id", None)
        if function_id:
            function_obj = Function.objects.get(id=int(function_id)).function_ids_users.all()
            function_list = []
            for i in range(len(function_obj)):
                function_list.append({"real_name": function_obj[i].real_name, "job_number": function_obj[i].job_number, "Serial": i+1})
            returnDict = {'status': 'success', "code": 200, "function_list": function_list}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        return render(request, "back_management/FunctionalGrouping.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = Function.objects.all().order_by('-create_time')

        data_list = [{'id': obj.id, 'describe': obj.describe, 'people': ", ".join([i.real_name for i in obj.function_ids_users.all()])} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 车辆流程
class VehicleProcess(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/VehicleProcess.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", "")  # 查询标题
        topic_id = request.POST.get("topic_id", None)
        print("VehicId: ", topic_id)
        # 流程删除
        if topic_id:
            print("开始删除流程")
            Vehic_obj = VehicleApply.objects.get(id=topic_id)
            Vehic_obj.vehicleauditrecord_set.all().delete()  # 清除审批列表
            Vehic_obj.vehicleuseinfo_set.all().delete()         # 清除出车记录
            Vehic_obj.already_users.clear()  # 清除已审批列表
            Vehic_obj.delete()
            if Vehic_obj.public_search:
                Vehic_obj.public_search.audit_users_already.clear()
                Vehic_obj.public_search.current_audit_users.clear()
                Vehic_obj.public_search.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        objs = VehicleApply.objects.filter(Q(subject__contains=search_data) |                                              # 用车事由
                                      Q(route__contains=search_data) |                                                     # 出行路线
                                      Q(travelers_names__contains=search_data) |                                           # 出行人员名字
                                      Q(field_leader__contains=search_data) |                                              # 出行领导名字
                                      Q(drivers__contains=search_data),                                                    # 司机
                                      state__in=["draft", "fg", "ybzr", "cgb", "refuse"]).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'Reasons': obj.subject, 'start_time': obj.start_time.strftime("%Y-%m-%d %H:%M"),
             'end_time': obj.end_time.strftime("%Y-%m-%d %H:%M"), 'Route': obj.route,
             'apply_people': obj.apply_user.real_name, "status": "分管领导" if obj.state == "draft" else "车队领导" if obj.state == "fg"
             else "车管办分管领导" if obj.state == "ybzr" else "结束" if obj.state == "cgb" else "退回",
             'approver': obj.current_audit_user.real_name if obj.current_audit_user else ""}
            for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 车辆申请详情页
class VehicleDetail(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        VehicId = request.GET.get("id", None)
        VehicObj = VehicleApply.objects.get(id=int(VehicId))
        ReturnData = {"apply": VehicObj.apply_user.real_name, "dep": VehicObj.apply_user.company.name,
                      "apply_time": VehicObj.create_time.strftime("%Y-%m-%d %H:%M"),
                      "start_time": VehicObj.start_time.strftime("%Y-%m-%d %H:%M"),
                      'end_time': VehicObj.end_time.strftime("%Y-%m-%d %H:%M"), 'Route': VehicObj.route,
                      "drivers": VehicObj.drivers,
                      'Reasons': VehicObj.subject, "use_people": VehicObj.field_leader,
                      "is_fix": "是" if VehicObj.is_fix else "否", "VehicObj": VehicObj, "vehicles": VehicObj.vehicles}
        audit_dic = {}
        for audit_obj in VehicObj.vehicleauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        return render(request, "back_management/VehicleDetail.html", {"ReturnData": ReturnData, "audit_dic": audit_dic})

    def post(self, request):
        """修改流程内容"""
        VehicId = request.POST.get("VehicId", None)              # 流程ID
        car_marks = request.POST.get("car_marks", None)          # 用车是由
        start_time = request.POST.get("start_time", None)          # 开始时间
        end_time = request.POST.get("end_time", None)             # 结束时间
        route = request.POST.get("route", None)                    # 行车路线
        field_leader = request.POST.get("field_leader", None)     # 用车人

        field_leader_list = field_leader.split(", ")
        name_list, job_number_list = [], []
        for i in field_leader_list:
            name_list.append(i.split("(")[0])
            job_number_list.append(i.split("(")[0][:-1])

        VehicObj = VehicleApply.objects.get(id=int(VehicId))
        VehicObj.subject = car_marks
        VehicObj.route = route
        VehicObj.start_time = start_time
        VehicObj.end_time = end_time
        VehicObj.field_leader_numbers = ", ".join(job_number_list)
        VehicObj.field_leader = ", ".join(name_list)
        VehicObj.save()
        returnDict = {'status': 'success', "code": 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

#
class VehicleManage(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/VehicleManage.html")

# 权限管理
class SuperSUPro(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/SuperSU_Pro.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", "")  # 查询标题

        bill_groups = BillGroup.objects.filter(Q(menu__contains=search_data) | Q(bill__contains=search_data) | Q(bill__contains=search_data) | Q(apply_user_name__contains=search_data))

        data_list = [
            {'id': obj.id, 'menu': obj.menu, 'bill': obj.bill, 'apply_user': obj.apply_user_name, "job_numbers": obj.apply_user,
             'groups': ', '.join([g.level for g in obj.groups.all()]), 'type': obj.get_type_display(),
             'operator_str': ', '.join([f"{obj.apply_user_name.split(', ')[i]}({obj.apply_user.split(', ')[i]})" for i in range(len(obj.apply_user_name.split(", ")))])
             } for obj in bill_groups[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": bill_groups.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 修改权限
class ModifyPermission(View):
    def post(self, request):
        id = request.POST.get("id", None)
        executor = request.POST.get("executor", None)
        groups_get = request.POST.get("groups", None)

        if id:
            b = BillGroup.objects.get(id=int(id))
            if executor:
                executor = re.findall('\((.*?)\)', executor)
                b.apply_user = ', '.join(executor)
                apply_user_list = [User.objects.get(job_number=user_str.strip()).real_name for user_str in executor]
                apply_user_str = ', '.join(apply_user_list)
                b.apply_user_name = apply_user_str
                b.save()
                b.executor.clear()
                for i in [User.objects.get(job_number=user_str.strip()) for user_str in executor]:
                    b.executor.add(i)
            if groups_get:
                groups = groups_get.split(',')
                b.groups.clear()
                for group in groups:
                    temp = Group.objects.get(level=group.strip())
                    if temp:
                        b.groups.add(temp)
        returnDict = {'status': 'success', "code": 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 角色管理
class RoleManagement(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/RoleManagement.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = Staffing.objects.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'user': ' ,'.join([i.real_name for i in obj.post_personnel.all()]), 'station': obj.station,
                      'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
                      'update_time': obj.update_time.strftime("%Y-%m-%d %H:%M")} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 角色修改
class modify_role(View):
    def post(self, request):
        role_id = request.POST.get("role_id", None)
        conferee = request.POST.get("conferee", 20)
        if int(role_id) == 27:
            Group.objects.get(id=2).user_set.all().update(group=Group.objects.get(id=6))
        objs = Staffing.objects.get(id=int(role_id))
        user_list = re.findall('\((.*?)\)', conferee)
        post_personnel_list = User.objects.filter(job_number__in=user_list)
        objs.post_personnel.clear()
        for i in post_personnel_list:
            objs.post_personnel.add(i)
            if int(role_id) == 27:
                i.group = Group.objects.get(id=2)
                i.save()

        returnDict = {'status': 'success', "code": 200, "data": [], 'message': "修改成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 上级来文列表
class DocumentsSuperList(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/DocumentsSuperList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = OfficialDocuments.objects.filter(Q(send_company__contains=search_data) | Q(title__contains=search_data) | Q(send_number__contains=search_data) |
                                                Q(send_company__contains=search_data) | Q(recive_number__contains=search_data) | Q(apply_user__real_name__contains=search_data) |
                                                Q(create_time__contains=search_data)).order_by('-create_time')

        review_list, distributed, return_list, circulation, end_list, cancel_list, stop_list, recall_list = [], [], [], [], [], [], [], []
        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            one_dict = {'id': obj.id, 'Communication': obj.send_company, 'title': obj.title, 'document_font': obj.send_number, 'type': obj.type,
                      'document_no': obj.recive_number, 'recipient': obj.apply_user.real_name, 'status': obj.get_state_str(), 'approver': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
                      'receiving_time': obj.create_time.strftime("%Y-%m-%d %H:%M")}
            if obj.type == "g":
                distributed.append(one_dict)
            elif obj.type == "f":
                return_list.append(one_dict)
            elif obj.type == "e":
                end_list.append(one_dict)
            elif obj.type == "d":
                circulation.append(one_dict)
            elif obj.type == "cancel":
                cancel_list.append(one_dict)
            elif obj.type == "stop":
                stop_list.append(one_dict)
            elif obj.type == "recall":
                recall_list.append(one_dict)
            else:
                review_list.append(one_dict)
        data_list = review_list + return_list + distributed + stop_list + recall_list + cancel_list + circulation + end_list
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 上级来文详情及修改
class ReceivedDetail(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/ReceivedDetail.html")

    def post(self, request):
        send_number = request.POST.get('send_number', None)
        recive_number = request.POST.get('recive_number', None)
        send_company = request.POST.get('send_company', None)
        title = request.POST.get('title', None)
        content = request.POST.get('content', None)
        annotated_text = request.POST.get('annotated_text', '')
        time_limit = request.POST.get('time_limit', '')
        beizhu = request.POST.get("beizhu", None)
        objs = OfficialDocuments.objects.get(recive_number=recive_number)
        objs.send_number = send_number
        objs.send_company = send_company
        objs.title = title
        objs.content = content
        objs.annotated_text = annotated_text
        objs.time_limit = time_limit
        objs.remarks = beizhu
        objs.save()
        returnDict = {'status': 'success', "code": 200, "data": []}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 添加收阅人
class AddRecipient(View):
    def post(self, request):
        process_id = request.POST.get("id", None)                   # 流程ID
        add_people = request.POST.get("add_people", None)           # 添加的接收人
        process_type = request.POST.get("type", None)               # 流程类型：LW,上级来文，反之内部公文

        items = []
        receive_people = re.findall('\((.*?)\)', add_people)
        receive_people_objs = User.objects.filter(job_number__in=receive_people)
        if process_type == "LW":
            obj = OfficialDocuments.objects.get(id=int(process_id))
            for receive_people_obj in receive_people_objs:
                off_obj = OfficialDocumentsPeople(notice_id=obj, state='accept', audit_people=receive_people_obj)
                items.append(off_obj)
            OfficialDocumentsPeople.objects.bulk_create(items)
        elif process_type == "TZ":
            obj = Notice.objects.get(id=int(process_id))
            for receive_people_obj in receive_people_objs:
                off_obj = NoticePeople(notice_id=obj, state='accept', audit_people=receive_people_obj)
                items.append(off_obj)
            NoticePeople.objects.bulk_create(items)
        else:
            obj = ConferenceMemo.objects.get(id=int(process_id))
            for user in receive_people_objs:
                obj = ConferenceMemoPeople(notice_id=obj, audit_people=user,
                                           real_name=user.real_name,
                                           signature_picture=str(user.signature_picture), state='accept')
                items.append(obj)
            ConferenceMemoPeople.objects.bulk_create(items)

        returnDict = {'status': 'success', "code": 200, "data": []}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 公文列表 && 删除公告
class DocumentList(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/DocumentList.html")

    def post(self, request):                # 删除公告
        notice_id = request.POST.get("id", None)
        document_obj = Notice.objects.get(id=int(notice_id))
        document_obj.delete()
        returnData = {'code': 200, 'message': '删除！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 获取公文列表
class GetDocumentList(View):
    def get(self, request):
        page = request.GET.get("cPage", 1)
        page_size = request.GET.get("pSize", 20)
        search_data = request.GET.get("search_data", '')  # 查询标题
        DocumentType = request.GET.get("type", None)         # 公文类型
        objs = ConferenceMemo.objects.filter(Q(conference_memo_text__contains=search_data) | Q(document_number__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                                             type=DocumentType).order_by('-create_time')
        data_list = [{'id': obj.id, 'title': obj.conference_memo_text, 'document_number': obj.document_number, 'type': obj.type, 'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
                      'apply_user': obj.apply_user.real_name, 'status': obj.get_state_str(), 'approver': ', '.join([i.real_name for i in obj.current_audit_users.all()]), 'drafted_user': obj.drafter}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):                # 公文删除
        document_id = request.POST.get("id", None)
        document_obj = ConferenceMemo.objects.get(id=int(document_id))
        if document_obj.type == "a":
            document_type = "会议纪要〔{}〕{}号"
        elif document_obj.type == "b":
            document_type = "会议纪要〔{}〕{}号"
        elif document_obj.type == "c":
            document_type = "会议纪要〔{}〕{}号"
        elif document_obj.type == "d":
            document_type = "会议纪要〔{}〕{}号"
        elif document_obj.type == "e":
            document_type = "行政例会〔{}〕{}号"
        elif document_obj.type == "f":
            document_type = "京医发〔{}〕{}号"
        elif document_obj.type == "g":
            document_type = "京医党发〔{}〕{}号"
        else:
            document_type = "京医文〔{}〕{}号"
        document_year = re.findall("〔(.*?)〕", document_obj.document_number, re.S)[0]

        objs = ConferenceMemo.objects.filter(type=document_obj.type).last()

        official_documents_objs = ConferenceMemo.objects.filter(create_time__range=[document_obj.create_time, objs.create_time], type=document_obj.type, document_year=document_year)
        for official_documents_obj in official_documents_objs[1:]:
                DocumentNumber = int(re.findall("〕(.*?)号", official_documents_obj.document_number, re.S)[0])-1
                official_documents_obj.document_number = document_type.format(document_year, DocumentNumber)
                official_documents_obj.save()

        document_obj.delete()
        returnData = {'code': 200, 'message': '删除！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 公文详情页 && 修改公文
class DocumentDetail(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/DocumentDetail.html")

    def post(self, request):
        conference_memo_text = request.POST.get('conference_memo_text', None)       # 标题
        servingsve_number = request.POST.get('servings', None)                      # 印份
        main_company = request.POST.get('main_company', None)                       # 主送
        vice_company = request.POST.get('vice_company', None)                       # 抄送
        yjtd = request.POST.get('yjtd', None)                                       # 依据
        press_id = request.POST.get('id', None)
        objs = ConferenceMemo.objects.get(id=int(press_id))
        objs.conference_memo_text = conference_memo_text
        objs.servingsve_number = servingsve_number
        objs.main_company = main_company
        objs.vice_company = vice_company
        objs.gist = yjtd
        objs.save()
        returnDict = {'status': 'success', "code": 200, "data": []}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 公告列表
class NoticeList(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/NoticeList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = Notice.objects.filter(Q(name__contains=search_data) | Q(create_people__real_name__contains=search_data) | Q(create_people__company__name__contains=search_data)).order_by('-create_time')
        data_list = [{'id': obj.id, 'title': obj.name, 'create_people': obj.create_people.real_name, 'dep': obj.create_people.company.name,
                      'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"), 'status': obj.get_state_str(), 'approver': obj.audit_people.real_name if obj.audit_people else "",
                      } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 公告详情页
class NoticeDetail(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/NoticeDetail.html")

# 自定义流程列表
class FormList(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/FormList.html")

class delete_flow_view(View):
    def post(self, request):
        flow_id = request.POST.get("flow_id", '')
        operate_type = request.POST.get("operate_type", '')
        obj = CustomerForm.objects.get(id=int(flow_id))
        if operate_type == 'delete':
            child_obj = obj.lowcodebill_set.all().count()
            if child_obj:
                returnDict = {'code': 400, 'status': 'success', 'message': "已有流程申请，无法删除！"}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            print("开始删除", flow_id)
            obj.delete()
        else:
            obj.abandoned = '1'
            obj.module = '历史数据管理'
            obj.save()
        returnDict = {'code': 200, 'status': 'success', 'message': "操作成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 物资流程
class MaterialProcess(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/MaterialProcess.html")

# 用印申请列表页
class SealApplicationList(View):
    def get(self, request):
        try:
            request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/SealApplicationList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = SealApply.objects.filter(Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data) | Q(seal_name__contains=search_data)
                                        , state__in=['one', 'two', 'three', 'four', 'seven', 'five', 'six', 'eight', 'nine', 'stop', 'ten']).order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'number': obj.number,
             'apply_user': obj.apply_user.real_name,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'state': obj.state,
             'seal_name': obj.seal_name,
             'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'matter_type_text': obj.matter_type_text,
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 用印申请删除、修改
class SealApplicationModification(View):
    def post(self, request):
        seal_id = request.POST.get('seal_id', None)     # 用印流程ID
        types = request.POST.get("type", None)          # 操作类型：delete，删除
        Seal_obj = SealApply.objects.get(id=seal_id)
        if types == 'delete':
            Seal_obj.sealapplyauditrecord_set.all().delete()  # 清除审批列表
            Seal_obj.current_audit_users.clear()             # 清除当前审批
            Seal_obj.audit_users_already.clear()                   # 清除已审批列表
            Seal_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get('state', None)
            audit_people = request.POST.get('audit_people', None)
            audit_people = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people)
            Seal_obj.current_audit_users.clear()
            print("state: ", state)
            if state == 'C/D':
                if not Seal_obj.sealapplyauditrecord_set.filter(node='C/D'):
                    returnDict = {'message': '该流程无该节点，无法退回！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Seal_obj.sealapplyauditrecord_set.all().delete()
                SealApplyAuditRecord.objects.create(node='C/D', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Seal_obj)
                Seal_obj.current_audit_users.add(audit_people_objs.first())
                Seal_obj.state = 'one'
                Seal_obj.save()
                SealApplyAuditRecord.objects.create(node='B', state='unaudit', audit_people=Seal_obj.apply_user.company.leaders_id, parent_id=Seal_obj)
                SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=Staffing.objects.get(station='印章管理员').post_personnel.all().first(), parent_id=Seal_obj)

            elif state == 'B':
                if not Seal_obj.sealapplyauditrecord_set.filter(node='B'):
                    returnDict = {'message': '该流程无该节点，无法退回！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Seal_obj.sealapplyauditrecord_set.filter(node__in=['B', 'BGS', 'YB', 'YZ', 'END']).delete()
                SealApplyAuditRecord.objects.create(node='B', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Seal_obj)
                Seal_obj.current_audit_users.add(audit_people_objs.first())
                Seal_obj.state = 'two'
                Seal_obj.save()
                SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=Staffing.objects.get(station='印章管理员').post_personnel.all().first(), parent_id=Seal_obj)

            elif state == 'BGS':
                if not Seal_obj.sealapplyauditrecord_set.filter(node='BGS'):
                    returnDict = {'message': '该流程无该节点，无法退回！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Seal_obj.sealapplyauditrecord_set.filter(node__in=['BGS', 'YB', 'YZ', 'END']).delete()
                SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Seal_obj)
                Seal_obj.current_audit_users.add(audit_people_objs.first())
                Seal_obj.state = 'four'
                Seal_obj.save()

            elif state == 'YB':
                if not Seal_obj.sealapplyauditrecord_set.filter(node='YB'):
                    returnDict = {'message': '该流程无该节点，无法退回！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Seal_obj.sealapplyauditrecord_set.filter(node__in=['YB', 'YZ', 'END']).delete()
                SealApplyAuditRecord.objects.create(node='YB', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Seal_obj)
                Seal_obj.current_audit_users.add(audit_people_objs.first())
                Seal_obj.state = 'three'
                Seal_obj.save()

            elif state == 'YZ':
                if not Seal_obj.sealapplyauditrecord_set.filter(node='YZ'):
                    returnDict = {'message': '该流程无该节点，无法退回！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Seal_obj.sealapplyauditrecord_set.filter(node__in=['YZ', 'END']).delete()
                SealApplyAuditRecord.objects.create(node='YZ', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Seal_obj)
                Seal_obj.current_audit_users.add(audit_people_objs.first())
                Seal_obj.state = 'seven'
                Seal_obj.save()

            elif state == 'sjk':
                if not Seal_obj.sealapplyauditrecord_set.filter(node='sjk'):
                    returnDict = {'message': '该流程无该节点，无法退回！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Seal_obj.sealapplyauditrecord_set.filter(node__in=['sjk', 'END']).delete()
                SealApplyAuditRecord.objects.create(node='sjk', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Seal_obj)
                Seal_obj.current_audit_users.add(audit_people_objs.first())
                Seal_obj.state = 'nine'
                Seal_obj.save()

            elif state == 'END':
                if not Seal_obj.sealapplyauditrecord_set.filter(node='END'):
                    returnDict = {'message': '该流程无该节点，无法退回！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Seal_obj.sealapplyauditrecord_set.filter(node__in=['END']).delete()
                SealApplyAuditRecord.objects.create(node='END', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Seal_obj)
                Seal_obj.current_audit_users.add(audit_people_objs.first())
                Seal_obj.state = 'eight'
                Seal_obj.save()

            else:
                Seal_obj.sealapplyauditrecord_set.all().delete()
                Seal_obj.current_audit_users.add(Seal_obj.apply_user)
                Seal_obj.state = 'six'
                Seal_obj.save()
                director_appave = Seal_obj.apply_user.company.head_people
                if Seal_obj.apply_user != director_appave:
                    SealApplyAuditRecord.objects.create(node='C/D', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Seal_obj)

                SealApplyAuditRecord.objects.create(node='B', state='unaudit', audit_people=Seal_obj.apply_user.company.leaders_id, parent_id=Seal_obj)
                SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=Staffing.objects.get(station='印章管理员').post_personnel.all().first(), parent_id=Seal_obj)
            Seal_obj.voucher = "0"
            Seal_obj.save()
            returnData = {'code': 200, 'message': '退回成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

# 用印申请详情页
class SealApplicationDetails(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = SealApply.objects.get(id=int(id))
        audit_dic = {}
        flow_dict = {}
        endappave = Staffing.objects.filter(station__in=('印章管理员', '党委印章管理员'))
        end_list = [i.post_personnel.all().first() for i in endappave]
        for audit_obj in obj.sealapplyauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                                  'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                              'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        main_file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"), "file_type": atta_obj.file_type,
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        seal_obj = seal.objects.all()
        if request.user.company.id in [3, 80, 8]:
            leaders_obj = User.objects.filter(group__id__in=[1, 2])
        else:
            leaders_obj = User.objects.filter(group__id=2)
        BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
        try:
            Bstep = audit_dic['B'][-1]['audit_user']
        except:
            Bstep = ''
        dzb_obj = Company.objects.get(id=3).head_people
        sjk_obj = Company.objects.get(id=22).head_people
        flag = 'false'
        for t in main_file_list:
            if t['file_type'] == '1':
                flag = 'true'

        quick_obj = QuickAuthorization.objects.filter(state='seven', HandledBy=request.user)
        str_list, SealList, JudgmentDictionary = [], [], {}
        if quick_obj.count():
            Quick = 'true'
            for Objs in quick_obj:
                for i in json.loads(Objs.reason):
                    if seal.objects.get(id=i["yinzhang"]).seal_name not in SealList:
                        SealList.append(seal.objects.get(id=i["yinzhang"]).seal_name)
                    if i['neirong'].strip():
                        str_list.append(i['neirong'].strip())

                    JudgmentDictionary[i['neirong'].strip()] = seal.objects.get(id=i["yinzhang"]).seal_name

        else:
            Quick = 'false'

        copy_obj = MakeCopy.objects.filter(type='a', process_id=int(id))
        copy_flag = 'ture' if copy_obj.count() else 'false'

        if obj.sealapplyauditrecord_set.filter(node="C/D"):
            apply_people = []
            apply = 'true'
            for obj_s in obj.sealapplyauditrecord_set.filter(node="C/D"):
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict["C/D"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        if obj.sealapplyauditrecord_set.filter(node="B"):
            apply_people = []
            apply = 'true'
            for obj_s in obj.sealapplyauditrecord_set.filter(node="B"):
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict["B"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        if obj.sealapplyauditrecord_set.filter(node="ys"):
            apply_people = []
            apply = 'true'
            for obj_s in obj.sealapplyauditrecord_set.filter(node="ys"):
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict["ys"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        if obj.sealapplyauditrecord_set.filter(node="sjk"):
            apply_people = []
            apply = 'true'
            for obj_s in obj.sealapplyauditrecord_set.filter(node="sjk"):
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict["sjk"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        if obj.sealapplyauditrecord_set.filter(node="BGS"):
            apply_people = []
            apply = 'true'
            for obj_s in obj.sealapplyauditrecord_set.filter(node="BGS"):
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict["BGS"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        if obj.sealapplyauditrecord_set.filter(node="stb"):
            apply_people = []
            apply = 'true'
            for obj_s in obj.sealapplyauditrecord_set.filter(node="stb"):
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict["stb"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        if obj.sealapplyauditrecord_set.filter(node="YB"):
            apply_people = []
            apply = 'true'
            for obj_s in obj.sealapplyauditrecord_set.filter(node="YB"):
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict["YB"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        if obj.sealapplyauditrecord_set.filter(node="YZ"):
            apply_people = []
            apply = 'true'
            for obj_s in obj.sealapplyauditrecord_set.filter(node="YZ"):
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict["YZ"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        if obj.sealapplyauditrecord_set.filter(node="END"):
            apply_people = []
            apply = 'true'
            for obj_s in obj.sealapplyauditrecord_set.filter(node="END"):
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict["END"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        if obj.sealapplyauditrecord_set.filter(node="audits"):
            apply_people = []
            apply = 'true'
            for obj_s in obj.sealapplyauditrecord_set.filter(node="audits"):
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict["audits"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        if obj.sealapplyauditrecord_set.filter(node="END_2"):
            apply_people = []
            apply = 'true'
            for obj_s in obj.sealapplyauditrecord_set.filter(node="END_2"):
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict["END_2"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        aleard_flag = "false"
        if obj.is_fast and obj.state not in ["five", "six"]:
            if 'ys' in audit_dic and request.user.real_name == audit_dic["ys"][0]["audit_user"]:
                aleard_flag = "true"
            if 'B' in audit_dic and request.user.real_name == audit_dic["B"][0]["audit_user"]:
                aleard_flag = "true"
            if 'C/D' in audit_dic and request.user.real_name == audit_dic["C/D"][0]["audit_user"]:
                aleard_flag = "true"

        data_dic = {'obj': obj, 'audit_dic': audit_dic, 'realname': request.user.real_name,
                    'position': request.user.post, 'department': obj.apply_user.company.name, 'SealList': SealList,
                    'main_file_list': main_file_list, 'is_edit': 'true', 'Quick': Quick, 'str_list': str_list,
                    'is_shelve': 'true' if obj.state == "shelve" and obj.sealapplyauditrecord_set.all().order_by("-update_time").first().audit_people == request.user else 'false',
                    'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'seven', 'eight', 'nine', 'eleven', 'twelve'] and request.user in obj.current_audit_users.all() else 'false',
                    'is_voucher': 'true' if BGS_appave == request.user and obj.voucher == '0' and obj.state == 'five' else 'false',
                    'leaders_obj': leaders_obj, 'Bstep': Bstep, 'sjk_obj': sjk_obj, "aleard_flag": aleard_flag,
                    'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'six', 'seven', 'eight', 'nine'] and request.user == obj.apply_user else 'false',
                    'user_obj': User.objects.filter(group_id=1), 'dzb_obj': dzb_obj, 'uuid': obj.fj_number,
                    'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                    'state': obj.state, 'flow_dict': flow_dict, "seal_obj": seal_obj, "flag": flag,
                    "copy_obj": copy_obj, "copy_flag": copy_flag, "JudgmentDictionary": JudgmentDictionary,
                    'print_flag': 'true' if (request.user in end_list) and obj.state == 'five' else 'flase', }
        return render(request, "back_management/SealApplicationDetails.html", data_dic)


class SealProcessModification(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')            # 流程ID
        servings = request.POST.get("servings", '')            # 用印份数
        seal_name = request.POST.get("seal_name", '')           # 印章名称
        credentials = request.POST.get("credentials", '')               # 证件名称
        matter_type_text = request.POST.get("matter_type_text", '')             # 用印事由
        note = request.POST.get("note", '')                         # 备注
        leader_select = request.POST.get("leader_select", '')           # 分管领导
        YDetail = request.POST.get("YDetail", '')                         # 用印详情
        FileType = request.POST.get("FileType", '')                         # 文件类型
        try:
            obj = SealApply.objects.get(id=int(flow_id))
            obj.servings = servings
            obj.FileType = FileType
            obj.credentials = credentials
            obj.seal_name = seal_name
            obj.matter_type_text = matter_type_text
            obj.YDetail = YDetail
            obj.note = note
            obj.save()
        except Exception as E:
            returnDict = {'status': 'err', "code": 400, "message": str(E)}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {'status': 'success', "code": 200, "message": "修改成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 差旅报销列表
class TravelReimbursementList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/TravelReimbursementList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_data", "")
        print(search_value)
        objs = TravelReimbursement.objects.filter(
            Q(applicat__real_name__contains=search_value) | Q(company__name__contains=search_value) | Q(business_matter__contains=search_value),
            state__in=['one', 'nine', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'stop'])

        objs = objs.order_by('-create_time')
        data_list = [{'id': obj.id, 'business_matter': obj.business_matter,
                      'travel_people': ", ".join([i.real_name for i in obj.travel_people.all()]),
                      'apply_time': obj.apply_time, 'vote_reluse': '是' if obj.vote_reluse == 'yes' else '否',
                      'business_days': obj.business_days, 'applicat': obj.applicat.real_name,
                      'total': obj.total, 'state': obj.get_state_str(),
                      'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
                      'url': f'travel_reimbursement.html?id={obj.id}' if obj.get_state_str() == '草稿' else f"travel_approval.html?id={obj.id}"}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 差旅报销详情页
class TravelReimbursementDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        trave_id = request.GET.get("id", None)
        if int(trave_id) > 58:
            trave_obj = TravelReimbursement.objects.get(id=int(trave_id))
            data_obj = {'apply_time': trave_obj.apply_time, "travel_people": ", ".join([i.real_name for i in trave_obj.travel_people.all()]),
                        "vote_reluse": trave_obj.vote_reluse,
                        "total_daxie": trave_obj.total_daxie, 'business_days': trave_obj.business_days,
                        'hotel_expense': trave_obj.hotel_expense, 'business_matter': trave_obj.business_matter,
                        'traffic_expense': trave_obj.traffic_expense, 'payee': trave_obj.payee,
                        'remarks': trave_obj.remarks, 'total': trave_obj.total,
                        'TotalList': json.loads(json.loads(trave_obj.reimburse_dict))['TotalList'],
                        'OtherList': json.loads(json.loads(trave_obj.reimburse_dict))['OtherList'],
                        'is_edit': 'true' if trave_obj.get_state_str() == '拒绝' else 'false',
                        'sp_company': trave_obj.AuditDepartment}
            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=trave_obj.uuid)]
            audit_dic, flow_dict = {}, {}
            for audit_obj in trave_obj.travelreimbursementauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in trave_obj.travelreimbursementauditrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
            out_obj = OutgoingCadresData.objects.filter(relevance="0", state="seven", apply_user=trave_obj.applicat).order_by("-create_time")  # 中层干部外出
            Tra_obj = TravelApply.objects.filter(relevance="0", state="five", apply_user=trave_obj.applicat).order_by("-create_time")  # 差旅申请
            Veh_obj = VehicleApply.objects.filter(relevance="0", state="cgb", apply_user=trave_obj.applicat).order_by("-create_time")  # 用车申请
            context = {'realname': real_name, 'position': request.user.post,
                       "department": request.user.company.name, "out_obj": out_obj, "Tra_obj": Tra_obj, "Veh_obj": Veh_obj,
                       'apply': trave_obj.applicat.real_name,
                       "company": trave_obj.applicat.company.name, 'uuid': trave_obj.uuid, 'file_list': file_list,
                       'data_obj': data_obj, "audit_dic": audit_dic,
                       "id": trave_id, "trave_obj": trave_obj, "flow_dict": flow_dict,
                       "file_path": Topicsattachments.objects.filter(topics_number=trave_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=trave_obj.uuid) else ""}
            return render(request, 'back_management/TravelReimbursementDetail1.html', context)

        else:
            trave_obj = TravelReimbursement.objects.get(id=int(trave_id))
            data_obj = {'apply_time': trave_obj.apply_time,
                        "travel_people": ", ".join([i.real_name for i in trave_obj.travel_people.all()]),
                        "vote_reluse": trave_obj.vote_reluse, "total_daxie": trave_obj.total_daxie,
                        'business_days': trave_obj.business_days, 'hotel_expense': trave_obj.hotel_expense,
                        'business_matter': trave_obj.business_matter, 'traffic_expense': trave_obj.traffic_expense,
                        'payee': trave_obj.payee,
                        'remarks': trave_obj.remarks, 'total': trave_obj.total,
                        'reimburse_dict': json.loads(json.loads(trave_obj.reimburse_dict)),
                        'is_edit': 'true' if trave_obj.get_state_str() == '拒绝' else 'false'}
            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=trave_obj.uuid)]
            audit_dic, flow_dict = {}, {}
            for audit_obj in trave_obj.travelreimbursementauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in trave_obj.travelreimbursementauditrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                                 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            context = {'realname': real_name, 'position': request.user.post,
                       "department": request.user.company.name,
                       'apply': trave_obj.applicat.real_name,
                       "company": trave_obj.applicat.company.name, 'uuid': trave_obj.uuid, 'file_list': file_list,
                       'data_obj': data_obj, "audit_dic": audit_dic,
                       "id": trave_id, "trave_obj": trave_obj, "flow_dict": flow_dict,
                       "file_path": Topicsattachments.objects.filter(topics_number=trave_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=trave_obj.uuid) else ""}
            return render(request, 'back_management/TravelReimbursementDetail.html', context)

    def post(self, request):
        TravelId = request.POST.get('TravelId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Travel_obj = TravelReimbursement.objects.get(id=TravelId)
        if types == 'delete':
            Travel_obj.travelreimbursementauditrecord_set.all().delete()  # 清除审批列表
            Travel_obj.current_audit_users.clear()  # 清除当前审批
            Travel_obj.audit_users_already.clear()  # 清除已审批列表
            Travel_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            Travel_obj.current_audit_users.clear()
            state = request.POST.get("state", None)             # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)            # 审批人
            cwk = Company.objects.get(id=23)
            two_audit_people = Staffing.objects.get(station="财务出纳").post_personnel.all().first()
            six_audit_people = Staffing.objects.get(station="财务支付").post_personnel.all().first()

            if float(Travel_obj.total.replace(",", '')) < 10000:
                five_people = ""
            elif 10000 < float(Travel_obj.total.replace(",", '')) < 200000:
                try:
                    five_people = Staffing.objects.get(station="院长").post_personnel.all().first()
                except Exception as E:
                    returnData = {'code': 500, 'message': '请创建院长的角色！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                try:
                    five_people = Staffing.objects.get(station="书记").post_personnel.all().first()
                except Exception as E:
                    returnData = {'code': 500, 'message': '请创建书记的角色！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

            if state == 'nine':
                if not Travel_obj.travelreimbursementauditrecord_set.filter(node='nine'):
                    returnDict = {'message': '该流程无该节点，无法退回！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

                Travel_obj.travelreimbursementauditrecord_set.filter(node__in=['nine', 'three', 'four', 'five', 'six']).delete()  # 清除审批列表
                Travel_obj.current_audit_users.clear()  # 清除当前审批

                if Travel_obj.SourceFunds == '1':
                    kjk = Company.objects.get(id=14)
                    kjk_director = kjk.head_people
                    TravelReimbursementAuditRecord.objects.create(node='nine', state='unaudit', audit_people=kjk_director, parent_id=Travel_obj)
                elif Travel_obj.SourceFunds == '2':
                    gwk = Company.objects.get(id=19)
                    gwk_director = gwk.head_people
                    TravelReimbursementAuditRecord.objects.create(node='nine', state='unaudit', audit_people=gwk_director, parent_id=Travel_obj)
                else:
                    pass

                three_setp = Company.objects.get(id=22).head_people
                TravelReimbursementAuditRecord.objects.create(node='three', state='unaudit', audit_people=three_setp, parent_id=Travel_obj)
                TravelReimbursementAuditRecord.objects.create(node='four', state='unaudit', audit_people=cwk.head_people, parent_id=Travel_obj)
                if five_people:
                    TravelReimbursementAuditRecord.objects.create(node='five', state='unaudit', audit_people=five_people, parent_id=Travel_obj)
                TravelReimbursementAuditRecord.objects.create(node='six', state='unaudit', audit_people=six_audit_people, parent_id=Travel_obj)

            elif state == 'two' or state == 'eight':
                Travel_obj.travelreimbursementauditrecord_set.filter(node__in=['two', 'nine', 'three', 'four', 'five', 'six']).delete()  # 清除审批列表
                Travel_obj.current_audit_users.clear()  # 清除当前审批
                TravelReimbursementAuditRecord.objects.create(node='two', state='unaudit', audit_people=two_audit_people, parent_id=Travel_obj)
                if state == 'two':
                    Travel_obj.current_audit_users.add(two_audit_people)  # 创建当前审批人
                else:
                    Travel_obj.current_audit_users.add(Travel_obj.applicat)  # 创建当前审批人

                if Travel_obj.SourceFunds == '1':
                    kjk = Company.objects.get(id=14)
                    kjk_director = kjk.head_people
                    TravelReimbursementAuditRecord.objects.create(node='nine', state='unaudit', audit_people=kjk_director, parent_id=Travel_obj)
                elif Travel_obj.SourceFunds == '2':
                    gwk = Company.objects.get(id=19)
                    gwk_director = gwk.head_people
                    TravelReimbursementAuditRecord.objects.create(node='nine', state='unaudit', audit_people=gwk_director, parent_id=Travel_obj)
                else:
                    pass

                three_setp = Company.objects.get(id=22).head_people
                TravelReimbursementAuditRecord.objects.create(node='three', state='unaudit', audit_people=three_setp, parent_id=Travel_obj)
                TravelReimbursementAuditRecord.objects.create(node='four', state='unaudit', audit_people=cwk.head_people, parent_id=Travel_obj)
                if five_people:
                    TravelReimbursementAuditRecord.objects.create(node='five', state='unaudit', audit_people=five_people, parent_id=Travel_obj)
                TravelReimbursementAuditRecord.objects.create(node='six', state='unaudit', audit_people=six_audit_people, parent_id=Travel_obj)

            elif state == 'three':
                Travel_obj.travelreimbursementauditrecord_set.filter(node__in=['three', 'four', 'five', 'six']).delete()  # 清除审批列表
                Travel_obj.current_audit_users.clear()  # 清除当前审批

                three_setp = Company.objects.get(id=22).head_people
                TravelReimbursementAuditRecord.objects.create(node='three', state='unaudit', audit_people=three_setp, parent_id=Travel_obj)
                TravelReimbursementAuditRecord.objects.create(node='four', state='unaudit', audit_people=cwk.head_people,
                                                              parent_id=Travel_obj)
                if five_people:
                    TravelReimbursementAuditRecord.objects.create(node='five', state='unaudit', audit_people=five_people, parent_id=Travel_obj)
                TravelReimbursementAuditRecord.objects.create(node='six', state='unaudit', audit_people=six_audit_people, parent_id=Travel_obj)

            elif state == 'four':
                Travel_obj.travelreimbursementauditrecord_set.filter(node__in=['four', 'five', 'six']).delete()  # 清除审批列表
                Travel_obj.current_audit_users.clear()  # 清除当前审批

                TravelReimbursementAuditRecord.objects.create(node='four', state='unaudit', audit_people=cwk.head_people, parent_id=Travel_obj)
                if five_people:
                    TravelReimbursementAuditRecord.objects.create(node='five', state='unaudit', audit_people=five_people, parent_id=Travel_obj)
                TravelReimbursementAuditRecord.objects.create(node='six', state='unaudit', audit_people=six_audit_people, parent_id=Travel_obj)

            elif state == 'five':
                if not Travel_obj.travelreimbursementauditrecord_set.filter(node='five'):
                    returnDict = {'message': '该流程无该节点，无法退回！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Travel_obj.travelreimbursementauditrecord_set.filter(node__in=['five', 'six']).delete()  # 清除审批列表
                Travel_obj.current_audit_users.clear()  # 清除当前审批

                TravelReimbursementAuditRecord.objects.create(node='five', state='unaudit', audit_people=five_people, parent_id=Travel_obj)
                TravelReimbursementAuditRecord.objects.create(node='six', state='unaudit', audit_people=six_audit_people, parent_id=Travel_obj)

            else:
                Travel_obj.travelreimbursementauditrecord_set.filter(node='six').delete()  # 清除审批列表
                Travel_obj.current_audit_users.clear()  # 清除当前审批
                TravelReimbursementAuditRecord.objects.create(node='six', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Travel_obj)
                Travel_obj.current_audit_users.add(audit_people_objs.first())  # 创建当前审批人

            Travel_obj.state = state
            Travel_obj.save()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 一般付款列表页
class RegularPaymentList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/RegularPaymentList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = GeneralFinance.objects.filter(
            Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data) | Q(title__contains=search_data),
            state__in=['one', 'two', 'three', 'four', 'five', 'seven', 'eight', 'stop']).order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'title': obj.title,
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'total_amount': obj.total_amount,
             "url": "general_finance_draft_view?id=" + str(
                 obj.id) if obj.state == 'draft' else "general_finance_detail_view?id=" + str(obj.id),
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 一般付款详情页
class RegularPaymentDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = GeneralFinance.objects.get(id=id)
        fujian_obj = Topicsattachments.objects.filter(topics_number=obj.fj_number)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.generalfinanceauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.generalfinanceauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in fujian_obj]
        leaders_obj = User.objects.filter(group_id=2)
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "detail_pay": json.loads(json.loads(obj.detail_pay)),
                   "audit_dic": audit_dic, "is_edit": "true", "leaders_obj": leaders_obj,
                   'file_path': fujian_obj.first().pdf_path.replace("\\", "/") if fujian_obj else "",
                   'flow_dict': flow_dict
                   }
        return render(request, 'back_management/RegularPaymentDetail.html', context)

    def post(self, request):
        RegularId = request.POST.get('RegularId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Regular_obj = GeneralFinance.objects.get(id=RegularId)
        if types == 'delete':
            Regular_obj.generalfinanceauditrecord_set.all().delete()  # 清除审批列表
            Regular_obj.current_audit_users.clear()  # 清除当前审批
            Regular_obj.audit_users_already.clear()  # 清除已审批列表
            Regular_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            Regular_obj.current_audit_users.clear()
            state = request.POST.get("state", None)             # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)            # 审批人
            cwk_obj = Company.objects.get(id=23)
            try:
                yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
            except Exception as e:
                returnDict = {'code': 500, 'message': '院长岗位未维护，请联系管理员维护'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            try:
                sj_obj = Staffing.objects.get(station='书记').post_personnel.all().first()
            except Exception as e:
                returnDict = {'code': 500, 'message': '书记岗位未维护，请联系管理员维护'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            try:
                gh_obj = Staffing.objects.get(station='工会主席').post_personnel.all().first()
            except Exception as e:
                returnDict = {'code': 500, 'message': '工会主席岗位未维护，请联系管理员维护'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            try:
                cwzf_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
            except Exception as e:
                returnDict = {'code': 500, 'message': '财务支付岗位未维护，请联系管理员维护'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            if state == 'one':
                four_setp = Regular_obj.generalfinanceauditrecord_set.filter(node='four').first().audit_people
                Regular_obj.generalfinanceauditrecord_set.all().delete()  # 清除审批列表
                Regular_obj.current_audit_users.clear()  # 清除当前审批
                Regular_obj.audit_users_already.clear()  # 清除已审批列表
                Regular_obj.current_audit_users.add(audit_people_objs.first())
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='one')
                Regular_obj.state = 'one'
                two_appave = cwk_obj.head_people
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=two_appave, audit_note='', state='unaudit', node='two')
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=Regular_obj.apply_user.company.leaders_id, audit_note='', state='unaudit', node='three')
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=four_setp, audit_note='', state='unaudit', node='four')
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='five')
            elif state == 'two':
                four_setp = Regular_obj.generalfinanceauditrecord_set.filter(node='four').first().audit_people
                Regular_obj.generalfinanceauditrecord_set.filter(node__in=['two', 'four', 'five']).delete()  # 清除审批列表
                Regular_obj.current_audit_users.clear()  # 清除当前审批
                Regular_obj.current_audit_users.add(audit_people_objs.first())
                Regular_obj.state = 'two'
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='two')
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=four_setp, audit_note='', state='unaudit', node='four')
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='five')
            elif state == 'three':
                four_setp = Regular_obj.generalfinanceauditrecord_set.filter(node='four').first().audit_people
                Regular_obj.generalfinanceauditrecord_set.filter(node__in=['two', 'three', 'four', 'five']).delete()  # 清除审批列表
                Regular_obj.current_audit_users.clear()  # 清除当前审批
                Regular_obj.current_audit_users.add(audit_people_objs.first())
                Regular_obj.state = 'three'
                two_appave = cwk_obj.head_people
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=two_appave, audit_note='', state='unaudit', node='two')
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='three')
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=four_setp, audit_note='', state='unaudit', node='four')
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='five')
            elif state == 'four':
                Regular_obj.generalfinanceauditrecord_set.filter(node__in=['four', 'five']).delete()  # 清除审批列表
                Regular_obj.current_audit_users.clear()  # 清除当前审批
                Regular_obj.current_audit_users.add(audit_people_objs.first())
                Regular_obj.state = 'four'
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='four')
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='five')
            elif state == 'five':
                Regular_obj.generalfinanceauditrecord_set.filter(node='five').delete()  # 清除审批列表
                Regular_obj.current_audit_users.clear()  # 清除当前审批
                Regular_obj.current_audit_users.add(audit_people_objs.first())
                Regular_obj.state = 'five'
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='five')
            else:
                four_setp = Regular_obj.generalfinanceauditrecord_set.filter(node='four').first().audit_people
                Regular_obj.generalfinanceauditrecord_set.all().delete()  # 清除审批列表
                Regular_obj.current_audit_users.clear()  # 清除当前审批
                Regular_obj.audit_users_already.clear()  # 清除已审批列表
                one_appave = Regular_obj.apply_user.company.head_people
                if Regular_obj.apply_user != one_appave:
                    GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=one_appave, audit_note='', state='unaudit', node='one')
                two_appave = cwk_obj.head_people
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=two_appave, audit_note='', state='unaudit', node='two')
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=Regular_obj.apply_user.company.leaders_id, audit_note='', state='unaudit', node='three')
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=four_setp, audit_note='', state='unaudit', node='four')
                GeneralFinanceAuditRecord.objects.create(parent_id=Regular_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='five')
                Regular_obj.state='eight'
                Regular_obj.current_audit_users.add(Regular_obj.apply_user)

            Regular_obj.save()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 固定资产/维修维保付款列表
class FixedMaintenanceList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/FixedMaintenanceList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = FixedAssets.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data) | Q(title__contains=search_data),
                                          state__in=['one', 'two', 'three', 'four', 'five', 'seven', 'six', 'stop']).order_by('-create_time')
        data_list = [{'id': obj.id,
                      'number': obj.number,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'title': obj.title,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": "fixed_assets_apply_draft_view?id=" + str(
                          obj.id) if obj.state == 'draft' else "fixed_assets_apply_detail_view?id=" + str(obj.id),
                      'state': obj.get_str_state(),
                      'financial': obj.financial,
                      'total_money': obj.total_money}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 固定资产/维修维保付款详情
class FixedMaintenanceDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get("id", None)
        obj = FixedAssets.objects.get(id=id)
        audit_dic = {}
        flow_dict = {}
        for audit_obj in obj.fixedassetsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.fixedassetsauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   'user_obj': User.objects.filter(group_id=1),
                   'detail_pay': json.loads(obj.detail_pay),
                   'flow_dict': flow_dict
                   }
        return render(request, 'back_management/FixedMaintenanceDetail.html', context)

    def post(self, request):
        FixedId = request.POST.get('FixedId', None)  # 固定资产/维修维保流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Fixed_obj = FixedAssets.objects.get(id=FixedId)
        if types == 'delete':
            Fixed_obj.fixedassetsauditrecord_set.all().delete()  # 清除审批列表
            Fixed_obj.current_audit_users.clear()  # 清除当前审批
            Fixed_obj.audit_users_already.clear()  # 清除已审批列表
            Fixed_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            Fixed_obj.current_audit_users.clear()
            state = request.POST.get("state", None)             # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)            # 审批人
            if state == 'one':
                one_obj = Fixed_obj.fixedassetsauditrecord_set.filter(node='SBKZ')
                if not one_obj:
                    returnDict = {'message': '该流程无该节点，无法退回！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                four_step = Fixed_obj.fixedassetsauditrecord_set.filter(node='SJ/YZ').first()
                Fixed_obj.fixedassetsauditrecord_set.all().delete()
                FixedAssetsAuditRecord.objects.create(node='SBKZ', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Fixed_obj)
                cwk_obj = Company.objects.get(id=23).head_people
                FixedAssetsAuditRecord.objects.create(node='CWKZ', state='unaudit', audit_people=cwk_obj, parent_id=Fixed_obj)
                FixedAssetsAuditRecord.objects.create(node='B', state='unaudit', audit_people=Fixed_obj.company.leaders_id, parent_id=Fixed_obj)
                FixedAssetsAuditRecord.objects.create(node='SJ/YZ', state='unaudit', audit_people=four_step.audit_people, parent_id=Fixed_obj)
                cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                FixedAssetsAuditRecord.objects.create(node='CWK', state='unaudit', audit_people=cn_obj, parent_id=Fixed_obj)
                Fixed_obj.current_audit_users.add(audit_people_objs.first())
                Fixed_obj.state = 'one'
                Fixed_obj.save()
            elif state == 'two':
                four_step = Fixed_obj.fixedassetsauditrecord_set.filter(node='SJ/YZ').first()
                Fixed_obj.fixedassetsauditrecord_set.filter(node__in=['CWKZ', 'B', 'SJ/YZ', 'CWK']).delete()
                FixedAssetsAuditRecord.objects.create(node='CWKZ', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Fixed_obj)
                FixedAssetsAuditRecord.objects.create(node='B', state='unaudit', audit_people=Fixed_obj.company.leaders_id, parent_id=Fixed_obj)
                FixedAssetsAuditRecord.objects.create(node='SJ/YZ', state='unaudit', audit_people=four_step.audit_people, parent_id=Fixed_obj)
                cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                FixedAssetsAuditRecord.objects.create(node='CWK', state='unaudit', audit_people=cn_obj, parent_id=Fixed_obj)
                Fixed_obj.current_audit_users.add(audit_people_objs.first())
                Fixed_obj.state = 'two'
                Fixed_obj.save()
            elif state == 'three':
                four_step = Fixed_obj.fixedassetsauditrecord_set.filter(node='SJ/YZ').first()
                Fixed_obj.fixedassetsauditrecord_set.filter(node__in=['B', 'SJ/YZ', 'CWK']).delete()
                FixedAssetsAuditRecord.objects.create(node='B', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Fixed_obj)
                FixedAssetsAuditRecord.objects.create(node='SJ/YZ', state='unaudit', audit_people=four_step.audit_people, parent_id=Fixed_obj)
                cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                FixedAssetsAuditRecord.objects.create(node='CWK', state='unaudit', audit_people=cn_obj, parent_id=Fixed_obj)
                Fixed_obj.current_audit_users.add(audit_people_objs.first())
                Fixed_obj.state = 'three'
                Fixed_obj.save()
            elif state == 'four':
                Fixed_obj.fixedassetsauditrecord_set.filter(node__in=['SJ/YZ', 'CWK']).delete()
                FixedAssetsAuditRecord.objects.create(node='SJ/YZ', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Fixed_obj)
                cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                FixedAssetsAuditRecord.objects.create(node='CWK', state='unaudit', audit_people=cn_obj, parent_id=Fixed_obj)
                Fixed_obj.current_audit_users.add(audit_people_objs.first())
                Fixed_obj.state = 'four'
                Fixed_obj.save()
            elif state == 'five':
                Fixed_obj.fixedassetsauditrecord_set.filter(node__in=['CWK']).delete()
                FixedAssetsAuditRecord.objects.create(node='CWK', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Fixed_obj)
                Fixed_obj.current_audit_users.add(audit_people_objs.first())
                Fixed_obj.state = 'five'
                Fixed_obj.save()
            else:
                Fixed_obj.current_audit_users.add(Fixed_obj.apply_user)
                Fixed_obj.state = 'seven'
                Fixed_obj.save()

            returnDict = {'message': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 差旅申请列表
class TravelApplicationList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/TravelApplicationList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = TravelApply.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data) | Q(subject__contains=search_data),
                                          state__in=['one', 'two', 'three', 'four', 'five', 'seven', 'six', 'eight', 'nine', 'stop']).order_by('-create_time')
        data_list = [{'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'state': obj.state,
             'travel_type': obj.get_travel_type_display(),
             'start_time': obj.start_time.split(" ")[0],
             'end_time': obj.end_time.split(" ")[0],
             'subject': obj.subject,
             'route': obj.route,
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 差旅申请详情页
class TravelApplicationDetail(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post, 'department': request.user.company.name}
        except:
            return redirect("/")
        id = request.GET.get('id', None)

        if int(id) < 260:
            revise = request.GET.get('revise', '')
            obj = TravelApply.objects.get(id=id)
            audit_dic, flow_dict = {}, {}
            for audit_obj in obj.travelapplyauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

            one_step = obj.travelapplyauditrecord_set.filter(node='one')
            if one_step:
                apply_people = []
                apply = 'true'
                for obj_s in one_step:
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict['one'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            four_step = obj.travelapplyauditrecord_set.filter(node__in=['six', 'seven', 'eight', 'nine'])
            if four_step:
                apply_people = []
                apply = 'true'
                for obj_s in four_step:
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict['two'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            two_step = obj.travelapplyauditrecord_set.filter(node='two')
            if two_step:
                apply_people = []
                apply = 'true'
                for obj_s in two_step:
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict['three'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                      'sear': len([i for i in flow_dict]) + 1}

            three_step = obj.travelapplyauditrecord_set.filter(node='three')
            if three_step:
                apply_people = []
                apply = 'true'
                for obj_s in three_step:
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict['four'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                     'sear': len([i for i in flow_dict]) + 1}

            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                       "audit_dic": audit_dic,
                       "is_edit": "true",
                       "flow_dict": flow_dict, "revise": revise,
                       "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""}
            return render(request, 'back_management/TravelApplicationDetailOld.html', context)

        revise = request.GET.get('revise', '')
        obj = TravelApply.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.travelapplyauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        one_step = obj.travelapplyauditrecord_set.filter(node='one')
        if one_step:
            apply_people = []
            apply = 'true'
            for obj_s in one_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['one'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        four_step = obj.travelapplyauditrecord_set.filter(node='two')
        if four_step:
            apply_people = []
            apply = 'true'
            for obj_s in four_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['two'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        two_step = obj.travelapplyauditrecord_set.filter(node='three')
        if two_step:
            apply_people = []
            apply = 'true'
            for obj_s in two_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['three'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        three_step = obj.travelapplyauditrecord_set.filter(node='four')
        if three_step:
            apply_people = []
            apply = 'true'
            for obj_s in three_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['four'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic,
                   "is_edit": "true",
                   "flow_dict": flow_dict, "revise": revise, 'report_dep': [i.id for  i in obj.ReportingDepartment.all()],
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""}
        return render(request, 'back_management/TravelApplicationDetail.html', context)

    def post(self, request):
        TravelId = request.POST.get('TravelId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Travel_obj = TravelApply.objects.get(id=TravelId)
        if types == 'delete':
            Travel_obj.travelapplyauditrecord_set.all().delete()  # 清除审批列表
            Travel_obj.current_audit_users.clear()  # 清除当前审批
            Travel_obj.audit_users_already.clear()  # 清除已审批列表
            Travel_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            Travel_obj.current_audit_users.clear()
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人

            if state == 'one' or state == 'eight':
                if state == 'one':
                    one_step = Travel_obj.travelapplyauditrecord_set.filter(node="one")
                    if not one_step:
                        returnDict = {'message': '该流程无该节点，无法退回！', "code": 400}
                        return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Travel_obj.travelapplyauditrecord_set.all().delete()
                Travel_obj.current_audit_users.clear()
                Travel_obj.audit_users_already.clear()
                flag, flag1, flag2 = True, True, True
                if state == 'one':
                    TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='one')
                    Travel_obj.current_audit_users.add(audit_people_objs.first())
                    Travel_obj.state = 'one'
                    flag = False
                else:
                    Travel_obj.state = 'eight'
                    one_appove = Travel_obj.company.head_people
                    Travel_obj.current_audit_users.add(Travel_obj.apply_user)
                    if Travel_obj.apply_user != one_appove:
                        TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=one_appove, audit_note='', state='unaudit', node='one')
                        flag = False

                if Travel_obj.travel_type == "one":
                    two_appove = Company.objects.get(id=14).head_people
                    TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=two_appove, audit_note='', state='unaudit', node='two')
                    if flag:
                        Travel_obj.current_audit_users.add(two_appove)
                        Travel_obj.state = 'two'
                        flag1 = False

                if Travel_obj.travel_type == "two":
                    two_appove = Company.objects.get(id=13).head_people
                    TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=two_appove, audit_note='', state='unaudit', node='two')
                    if flag:
                        Travel_obj.current_audit_users.add(two_appove)
                        Travel_obj.state = 'two'
                        flag1 = False

                ReportingDepartment = Travel_obj.ReportingDepartment.all()
                for i in ReportingDepartment:
                    if i.id == 3:
                        TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=i.head_people, audit_note='', state='unaudit', node='three')
                        if flag and flag1:
                            Travel_obj.current_audit_users.add(i.head_people)
                            Travel_obj.state = 'three'
                            flag2 = False
                    if i.id == 13:
                        TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=i.head_people, audit_note='', state='unaudit', node='three')
                        if flag and flag1:
                            Travel_obj.current_audit_users.add(i.head_people)
                            Travel_obj.state = 'three'
                            flag2 = False
                    if i.id == 15:
                        TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=i.head_people, audit_note='', state='unaudit', node='three')
                        if flag and flag1:
                            Travel_obj.current_audit_users.add(i.head_people)
                            Travel_obj.state = 'three'
                            flag2 = False

                TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=Travel_obj.company.leaders_id, audit_note='', state='unaudit', node='four')
                if flag and flag1 and flag2:
                    Travel_obj.current_audit_users.add(Travel_obj.company.leaders_id)
                    Travel_obj.state = 'four'
                Travel_obj.save()

            elif state == 'two':
                Travel_obj.travelapplyauditrecord_set.filter(node__in=['two', 'three', 'four']).delete()
                TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='two')
                Travel_obj.current_audit_users.add(audit_people_objs.first())
                Travel_obj.state = 'two'

                ReportingDepartment = Travel_obj.ReportingDepartment.all()
                for i in ReportingDepartment:
                    if i.id == 3:
                        TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=i.head_people, audit_note='', state='unaudit', node='three')
                    if i.id == 13:
                        TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=i.head_people, audit_note='', state='unaudit', node='three')
                    if i.id == 15:
                        TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=i.head_people, audit_note='', state='unaudit', node='three')
                TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=Travel_obj.company.leaders_id, audit_note='', state='unaudit', node='four')

            elif state == 'three':
                Travel_obj.travelapplyauditrecord_set.filter(node__in=['three', 'four']).delete()
                for audit in audit_people_objs:
                    TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=audit, audit_note='', state='unaudit', node='three')
                    Travel_obj.current_audit_users.add(audit)
                Travel_obj.state = 'three'
                TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=Travel_obj.company.leaders_id, audit_note='', state='unaudit', node='four')

            else:
                Travel_obj.travelapplyauditrecord_set.filter(node__in=['four']).delete()
                Travel_obj.state = 'four'
                Travel_obj.current_audit_users.add(audit_people_objs.first())
                TravelApplyAuditRecord.objects.create(parent_id=Travel_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='four')

            Travel_obj.save()
            returnDict = {'message': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 合同会签列表页
class ContractCountersignatureList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/ContractCountersignatureList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        select_sql = f"SELECT * FROM (SELECT A.id, B.real_name, C.`name`, A.create_time, A.contract_name, A.contract_number, CASE WHEN A.contract_type = '1' THEN '服务类' WHEN A.contract_type = '2' THEN '货物类' WHEN A.contract_type = '3' THEN '工程类' ELSE '其它类' END AS 'contract_type', CASE WHEN A.state = 'stop' THEN '终止' WHEN A.state = 'seven' THEN '结束' WHEN A.state = 'eight' THEN '拒绝' ELSE '审核中' END AS status, AA.user_id AS approved, CONCAT( '/back-management/ContractCountersignatureDetail.html?id=', A.id ) AS url FROM `finance_businesscontract` A LEFT JOIN finance_businesscontract_current_audit_users AA ON A.id=AA.businesscontract_id LEFT JOIN tb_users_message B ON A.apply_user_id = B.id LEFT JOIN administrative_company C ON A.company_id = C.id LEFT JOIN administrative_company D ON A.product_company_id = D.id WHERE A.state IN ( 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'stop' ) UNION ALL SELECT Z.id, Y.real_name, X.`name`, Z.create_time, W.contract_name, W.contract_number, CASE WHEN W.contract_type = '1' THEN '服务类' WHEN W.contract_type = '2' THEN '货物类' WHEN W.contract_type = '3' THEN '工程类' ELSE '其它类' END AS 'contract_type', CASE WHEN Z.state = 'end' THEN '结束' WHEN Z.state = 'eight' THEN '拒绝' WHEN Z.state = 'stop' THEN '终止' ELSE '审核中' END AS status, ZZ.user_id AS approved, CONCAT( '/back-management/ContractCountersignatureDetailNew.html?id=', Z.id ) AS url FROM `administrative_contractapproval` Z LEFT JOIN administrative_contractapproval_current_audit_users ZZ ON ZZ.contractapproval_id = Z.id LEFT JOIN tb_users_message Y ON Z.apply_user_id = Y.id LEFT JOIN administrative_company X ON Y.company_id = X.id LEFT JOIN administrative_topics W ON Z.topics_id_id = W.id WHERE Z.state IN ( 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'stop', 'end' )) base ORDER BY create_time DESC"
        with connection.cursor() as cursor:
            cursor.execute(select_sql)
            objs = cursor.fetchall()

        data_list = []
        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            currt_people = User.objects.get(id=int(obj[8])).real_name if obj[8] else ""
            one_dict = {'id': obj[0], 'apply_user': obj[1], 'company': obj[2], 'create_time': obj[3].strftime("%Y-%m-%d %H:%M"), 'contract_name': obj[4], 'contract_number': obj[5],
             'contract_type': obj[6], 'state_display': obj[7], 'current_audit_users': currt_people, "url": obj[9]
             }
            data_list.append(one_dict)
        returnDict = {'status': 'success', "totals": len(objs), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 合同会签详情页
class ContractCountersignatureDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = BusinessContract.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.businesscontractauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.businesscontractauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "file_type": atta_obj.file_type,
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        flag = 'flase'
        for t in file_list:
            if t['file_type'] == '1':
                flag = 'true'

        if obj.product_company.id == 87:
            xuqiu_dep, xuqiu_id = [], []
            for tt in obj.requirement_department.all():
                xuqiu_dep.append(tt.name)
                xuqiu_id.append(str(tt.id))
        else:
            xuqiu_dep, xuqiu_id = [obj.product_company.name], [str(obj.product_company.id)]

        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic, "flag": flag, "xuqiu_dep_str": ", ".join(xuqiu_dep), "xuqiu_id_str": ", ".join(xuqiu_id),
                   "is_edit": "true",
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "", "flow_dict": flow_dict,
                   'company_list': [{"id": c.id, "name": c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")]
                   }
        return render(request, 'back_management/ContractCountersignatureDetail.html', context)

    def post(self, request):
        ContractId = request.POST.get('ContractId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Contract_obj = BusinessContract.objects.get(id=ContractId)
        if types == 'delete':
            Contract_obj.businesscontractauditrecord_set.all().delete()  # 清除审批列表
            Contract_obj.current_audit_users.clear()  # 清除当前审批
            Contract_obj.audit_users_already.clear()  # 清除已审批列表
            Contract_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            Contract_obj.current_audit_users.clear()
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人
            if state == 'one' or state == 'eight':
                Contract_obj.businesscontractauditrecord_set.all().delete()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='one')
                if Contract_obj.state == 'eight':
                    Contract_obj.current_audit_users.add(Contract_obj.apply_user)
                else:
                    Contract_obj.current_audit_users.add(audit_people_objs.first())
                Contract_obj.state = state

                two_audit = Contract_obj.product_company.head_people
                if audit_people_objs.first() != two_audit:
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=two_audit, audit_note='', state='unaudit', node='two')

                three_audit = Company.objects.get(id=23).head_people
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=three_audit, audit_note='', state='unaudit', node='three')

                jcs_user = Company.objects.get(id=18).head_people
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=jcs_user, audit_note='', state='unaudit', node='four')

                five_audit = Company.objects.get(id=22).head_people
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=five_audit, audit_note='', state='unaudit', node='five')

                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Contract_obj.company.leaders_id, audit_note='', state='unaudit', node='six')

                if Contract_obj.greater == '1':
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), audit_note='', state='unaudit', node='nine')
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='ten')
                else:
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='nine')

                BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=BGS_appave, audit_note='', state='unaudit', node='eleven' )

            elif state == 'two':
                Contract_obj.businesscontractauditrecord_set.filter(node__in=['two', 'three', 'four', 'five', 'six', 'nine', 'ten', 'eleven']).delete()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='two')
                Contract_obj.current_audit_users.add(audit_people_objs.first())
                Contract_obj.state = state

                three_audit = Company.objects.get(id=23).head_people
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=three_audit, audit_note='', state='unaudit', node='three')

                jcs_user = Company.objects.get(id=18).head_people
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=jcs_user, audit_note='', state='unaudit', node='four')

                five_audit = Company.objects.get(id=22).head_people
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=five_audit, audit_note='', state='unaudit', node='five')

                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Contract_obj.company.leaders_id, audit_note='', state='unaudit', node='six')
                if Contract_obj.greater == '1':
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), audit_note='', state='unaudit', node='nine')
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='ten')
                else:
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='nine')
                BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=BGS_appave, audit_note='', state='unaudit', node='eleven')

            elif state == 'three':
                Contract_obj.businesscontractauditrecord_set.filter(node__in=['three', 'four', 'five', 'six', 'nine', 'ten', 'eleven']).delete()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='three')
                Contract_obj.current_audit_users.add(audit_people_objs.first())
                Contract_obj.state = state

                jcs_user = Company.objects.get(id=18).head_people
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=jcs_user, audit_note='', state='unaudit', node='four')

                five_audit = Company.objects.get(id=22).head_people
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=five_audit, audit_note='', state='unaudit', node='five')

                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Contract_obj.company.leaders_id, audit_note='', state='unaudit', node='six')
                if Contract_obj.greater == '1':
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), audit_note='', state='unaudit', node='nine')
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='ten')
                else:
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='nine')
                BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=BGS_appave, audit_note='', state='unaudit', node='eleven')

            elif state == 'four':
                Contract_obj.businesscontractauditrecord_set.filter(node__in=['four', 'five', 'six', 'nine', 'ten', 'eleven']).delete()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='four')
                Contract_obj.current_audit_users.add(audit_people_objs.first())
                Contract_obj.state = state

                five_audit = Company.objects.get(id=22).head_people
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=five_audit, audit_note='', state='unaudit', node='five')

                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Contract_obj.company.leaders_id, audit_note='', state='unaudit', node='six')
                if Contract_obj.greater == '1':
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), audit_note='', state='unaudit', node='nine')
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='ten')
                else:
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='nine')
                BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=BGS_appave, audit_note='', state='unaudit', node='eleven')

            elif state == 'five':
                Contract_obj.businesscontractauditrecord_set.filter(node__in=['five', 'six', 'nine', 'ten', 'eleven']).delete()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='five')
                Contract_obj.current_audit_users.add(audit_people_objs.first())
                Contract_obj.state = state

                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Contract_obj.company.leaders_id, audit_note='', state='unaudit', node='six')
                if Contract_obj.greater == '1':
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), audit_note='', state='unaudit', node='nine')
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='ten')
                else:
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='nine')
                BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=BGS_appave, audit_note='', state='unaudit', node='eleven')

            elif state == 'six':
                Contract_obj.businesscontractauditrecord_set.filter(node__in=['six', 'nine', 'ten', 'eleven']).delete()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='six')
                Contract_obj.current_audit_users.add(audit_people_objs.first())
                Contract_obj.state = state

                if Contract_obj.greater == '1':
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), audit_note='', state='unaudit', node='nine')
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='ten')
                else:
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='nine')
                BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=BGS_appave, audit_note='', state='unaudit', node='eleven')

            elif state == 'nine':
                Contract_obj.businesscontractauditrecord_set.filter(node__in=['nine', 'ten', 'eleven']).delete()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='nine')
                Contract_obj.current_audit_users.add(audit_people_objs.first())
                Contract_obj.state = state

                if Contract_obj.greater == '1':
                    BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='ten')

                BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=BGS_appave, audit_note='', state='unaudit', node='eleven')

            elif state == 'ten':
                Contract_obj.businesscontractauditrecord_set.filter(node__in=['ten', 'eleven']).delete()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='ten')
                Contract_obj.current_audit_users.add(audit_people_objs.first())
                Contract_obj.state = state

                BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=BGS_appave, audit_note='', state='unaudit', node='eleven')

            else:
                Contract_obj.businesscontractauditrecord_set.filter(node__in=['eleven']).delete()
                BusinessContractAuditRecord.objects.create(parent_id=Contract_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='eleven')
                Contract_obj.current_audit_users.add(audit_people_objs.first())
                Contract_obj.state = state

        Contract_obj.save()
        returnDict = {'message': 'success', "code": 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ContractCountersignatureDetailNew(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ContractApproval.objects.get(id=id)
        audit_dic = {}
        topics_obj = obj.topics_id
        for audit_obj in topics_obj.topicsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        main_file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"), "pdf_path": atta_obj.pdf_path, "file_type": "0",
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3], "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=topics_obj.uuid, file_type="0")]

        file_flag, protocol_flag = "false", "false"

        for iiii in Topicsattachments.objects.filter(topics_number=obj.fj_number):
            if iiii.file_type == '1':
                file_flag = "true"
            if iiii.file_type == '3':
                protocol_flag = "true"
            main_file_list.append(
                {"file_name": iiii.file_name if iiii.file_name else iiii.file_path.name.split('/')[-1],
                 "file_path": iiii.pdf_path.replace("\\", "/"), "pdf_path": iiii.pdf_path, "file_type": iiii.file_type,
                 "word_path": iiii.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": iiii.file_size, "uploader": iiii.uploader_user.real_name, "upload_time": str(iiii.create_time).split(".")[0][:-3], "id": iiii.id}
            )

        topic_audit_dic, topic_flow_dict = {}, {}
        for audit_obj in obj.contractapprovalrecord_set.all():
            if audit_obj.node in topic_audit_dic:
                topic_audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                        'state_display': audit_obj.get_state_display(),
                                                        'state': audit_obj.state, 'node': audit_obj.node,
                                                        'node_display': audit_obj.get_node_display(),
                                                        'audit_note': audit_obj.audit_note,
                                                        'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                        'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.contractapprovalrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                topic_flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in topic_flow_dict]) + 1}
                topic_audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                     'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        help_department = ' ,'.join([i.name for i in topics_obj.help_department.all()])
        help_department1 = ' ,'.join([f"{i.name}({i.id})" for i in topics_obj.help_department.all()])
        if Topicsattachments.objects.filter(topics_number=topics_obj.uuid):
            file_path = Topicsattachments.objects.filter(topics_number=topics_obj.uuid).first().pdf_path.replace("\\", "/")
        elif Topicsattachments.objects.filter(topics_number=obj.fj_number):
            file_path = Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/")
        else:
            file_path = ""
        print("===============", topics_obj.get_funding_source())
        data_dic = {'realname': real_name, 'position': request.user.post, 'department': request.user.company.name,
                    'apply_user': topics_obj.employee.real_name, 'state': topics_obj.get_state_display(),
                    'main_file_list': main_file_list, 'number': topics_obj.number,
                    'topics_name': topics_obj.topics_name, 'protocol_flag': protocol_flag,
                    'FundingSource': topics_obj.get_funding_source(),
                    'topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_text).decode()).decode()),
                    'topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_basis).decode()).decode()),
                    'solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.solution).decode()).decode()) if topics_obj.solution != "空" else "",
                    'db_topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_text).decode()).decode()) if topics_obj.db_topics_text else "",
                    'db_topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_basis).decode()).decode()) if topics_obj.db_topics_basis else "",
                    'db_solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_solution).decode()).decode()) if topics_obj.db_solution else "",
                    'topics_estimate': topics_obj.topics_estimate, 'help_department': help_department,
                    'help_department1': help_department1, "file_flag": file_flag, 'jfly': topics_obj.jfly if topics_obj.jfly else "",
                    'ysje': topics_obj.ysje if topics_obj.ysje else "", "uuid": uuid.uuid4(),
                    'audit_list': audit_dic, "topic_audit_dic": topic_audit_dic, "topic_flow_dict": topic_flow_dict, "obj": topics_obj, "flow_obj": obj,
                    'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false', "file_uuid": uuid.uuid4(),
                    'is_audit': 'true' if obj.state in ['negative', 'zero', 'one', 'two', 'three', 'four', 'five', "six", "seven"] and request.user in obj.current_audit_users.all() else 'false',
                    'is_stop': 'true' if obj.state in ['negative', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', "seven"] and request.user == obj.apply_user else 'false',
                    'file_path': file_path}
        return render(request, 'back_management/ContractCountersignatureDetailNew.html', data_dic)


# 材料付款列表页
class MaterialPaymentList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/MaterialPaymentList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = MedicalMaterials.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data) | Q(title__contains=search_data),
                                          state__in=['one', 'two', 'three', 'four', 'five', 'seven', 'six', 'eight', 'stop']).order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'title': obj.title,
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'total_amount': obj.total_amount,
             'source': obj.source,
             "url": "medical_materials_draft_view?id=" + str(obj.id) if obj.state == 'draft' else "medical_materials_detail_view?id=" + str(obj.id),
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 材料付款详情页
class MaterialPaymentDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = MedicalMaterials.objects.get(id=id)
        fujian_obj = Topicsattachments.objects.filter(topics_number=obj.fj_number)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.medicalmaterialsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.medicalmaterialsauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in fujian_obj]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic,
                   "detail_pay": json.loads(obj.detail_pay),
                   'file_path': fujian_obj.first().pdf_path.replace("\\", "/") if fujian_obj else "",
                   'flow_dict': flow_dict
                   }
        return render(request, "back_management/MaterialPaymentDetail.html", context)

    def post(self, request):
        MaterialId = request.POST.get('MaterialId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        print(MaterialId)
        Material_obj = MedicalMaterials.objects.get(id=MaterialId)
        if types == 'delete':
            Material_obj.medicalmaterialsauditrecord_set.all().delete()  # 清除审批列表
            Material_obj.current_audit_users.clear()  # 清除当前审批
            Material_obj.audit_users_already.clear()  # 清除已审批列表
            Material_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人
            cwk_obj = Company.objects.get(id=23)
            accounting = re.findall('\((.*?)\)', Material_obj.accounting)[0]
            clkj_obj = User.objects.get(id=int(accounting))
            try:
                yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
            except Exception as e:
                returnDict = {'code': 500, 'message': '院长岗位未维护，请联系管理员维护'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            try:
                sj_obj = Staffing.objects.get(station='书记').post_personnel.all().first()
            except Exception as e:
                returnDict = {'code': 500, 'message': '书记岗位未维护，请联系管理员维护'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            try:
                gh_obj = Staffing.objects.get(station='工会主席').post_personnel.all().first()
            except Exception as e:
                returnDict = {'code': 500, 'message': '工会主席岗位未维护，请联系管理员维护'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            try:
                cwzf_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
            except Exception as e:
                returnDict = {'code': 500, 'message': '财务支付岗位未维护，请联系管理员维护'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            cwk_director = cwk_obj.head_people                                                        # 财务科负责人
            total_amount = float(Material_obj.total_amount.replace(",", ''))
            if state == 'one' or state == 'eight':
                if state == 'one' and not Material_obj.medicalmaterialsauditrecord_set.filter(node='one'):
                    returnDict = {'message': '申请人为科室负责人，无法退回到该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Material_obj.medicalmaterialsauditrecord_set.all().delete()
                Material_obj.current_audit_users.clear()
                flag = True
                if state == 'eight':
                    if Material_obj.medicalmaterialsauditrecord_set.filter(node='one'):
                        MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=Material_obj.company.head_people, audit_note='', state='unaudit', node='one')
                        Material_obj.current_audit_users.add(Material_obj.apply_user)
                        flag = False
                else:
                    one_audit_people = audit_people_objs.first()
                    Material_obj.current_audit_users.add(one_audit_people)
                    MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=one_audit_people, audit_note='', state='unaudit', node='one')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=clkj_obj, audit_note='', state='unaudit', node='two')
                if flag:
                    Material_obj.current_audit_users.add(clkj_obj)
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=cwk_director, audit_note='', state='unaudit', node='three')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=Material_obj.company.leaders_id, audit_note='', state='unaudit', node='four')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=sj_obj if total_amount >= 200000 else yz_obj if 200000 > total_amount >= 10000 else gh_obj, audit_note='', state='unaudit', node='five')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')

                Material_obj.state = state
                Material_obj.save()
            elif state == 'two':
                Material_obj.current_audit_users.clear()
                Material_obj.medicalmaterialsauditrecord_set.filter(node__in=['two', 'three', 'four', 'five', 'six']).delete()
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='two')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=cwk_director, audit_note='', state='unaudit', node='three')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=Material_obj.company.leaders_id, audit_note='', state='unaudit', node='four')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=sj_obj if total_amount >= 200000 else yz_obj if 200000 > total_amount >= 10000 else gh_obj, audit_note='', state='unaudit', node='five')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')
                Material_obj.current_audit_users.add(audit_people_objs.first())
                Material_obj.accounting = f"{audit_people_objs.first().real_name}({audit_people_objs.first().id})"
                Material_obj.state = state
                Material_obj.save()
            elif state == 'three':
                Material_obj.current_audit_users.clear()
                Material_obj.medicalmaterialsauditrecord_set.filter(node__in=['three', 'four', 'five', 'six']).delete()
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='three')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=Material_obj.company.leaders_id, audit_note='', state='unaudit', node='four')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=sj_obj if total_amount >= 200000 else yz_obj if 200000 > total_amount >= 10000 else gh_obj, audit_note='', state='unaudit', node='five')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')
                Material_obj.current_audit_users.add(audit_people_objs.first())
                Material_obj.state = state
                Material_obj.save()
            elif state == 'four':
                Material_obj.current_audit_users.clear()
                Material_obj.medicalmaterialsauditrecord_set.filter(node__in=['four', 'five', 'six']).delete()
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='four')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=sj_obj if total_amount >= 200000 else yz_obj if 200000 > total_amount >= 10000 else gh_obj, audit_note='', state='unaudit', node='five')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')
                Material_obj.current_audit_users.add(audit_people_objs.first())
                Material_obj.state = state
                Material_obj.save()
            elif state == 'five':
                Material_obj.current_audit_users.clear()
                Material_obj.medicalmaterialsauditrecord_set.filter(node__in=['five', 'six']).delete()
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='five')
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')
                Material_obj.current_audit_users.add(audit_people_objs.first())
                Material_obj.state = state
                Material_obj.save()
            else:
                Material_obj.current_audit_users.clear()
                Material_obj.medicalmaterialsauditrecord_set.filter(node__in=['six']).delete()
                MedicalMaterialsAuditRecord.objects.create(parent_id=Material_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='six')
                Material_obj.current_audit_users.add(audit_people_objs.first())
                Material_obj.state = state
                Material_obj.save()

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 合同付款列表页
class ContractPaymentList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/ContractPaymentList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = LogisticsOffice.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data) | Q(pay_reason__contains=search_data),
                                          state__in=['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'stop']).order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'apply_user': obj.apply_user.real_name,
             'company': obj.company.name,
             'pay_reason': obj.pay_reason,
             'date': obj.create_time.strftime("%Y-%m-%d"),
             'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
             "url": "logistics_office_apply_draft_view?id=" + str(
                 obj.id) if obj.state == 'draft' else "logistics_office_apply_detail_view?id=" + str(obj.id),
             'state': obj.get_str_state(),
             'total_money': obj.total_money}
            for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 合同付款详情页
class ContractPaymentDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = LogisticsOffice.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.logisticsofficeauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.logisticsofficeauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'user_obj': User.objects.filter(group_id=1),
                   'flow_dict': flow_dict, 'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, "back_management/ContractPaymentDetail.html", context)

    def post(self, request):
        ContractId = request.POST.get('ContractId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Contract_obj = LogisticsOffice.objects.get(id=ContractId)
        if types == 'delete':
            Contract_obj.logisticsofficeauditrecord_set.all().delete()  # 清除审批列表
            Contract_obj.current_audit_users.clear()  # 清除当前审批
            Contract_obj.audit_users_already.clear()  # 清除已审批列表
            Contract_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人

            if state == 'zero' or state == 'eight':
                if state == 'zero' and not Contract_obj.logisticsofficeauditrecord_set.filter(node='zero'):
                    returnDict = {'message': '申请人为科室负责人，无法退回到该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                kuaiji_flag = False
                if Contract_obj.logisticsofficeauditrecord_set.filter(node='zero'):
                    kuaiji_flag = True
                Contract_obj.current_audit_users.clear()
                Contract_obj.logisticsofficeauditrecord_set.all().delete()
                one_appave = Contract_obj.company.head_people
                if state == 'zero':
                    LogisticsOfficeAuditRecord.objects.create(node='zero', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Contract_obj)
                    Contract_obj.current_audit_users.add(audit_people_objs.first())
                else:
                    Contract_obj.current_audit_users.add(Contract_obj.apply_user)
                    if kuaiji_flag:
                        htkj_obj = Staffing.objects.get(station='合同付款会计').post_personnel.all()
                        for htkj in htkj_obj:
                            LogisticsOfficeAuditRecord.objects.create(node='zero', state='unaudit', audit_people=htkj, parent_id=Contract_obj)

                if one_appave != Contract_obj.apply_user:
                    LogisticsOfficeAuditRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, parent_id=Contract_obj)

                two_appave = Company.objects.get(id=22).head_people
                LogisticsOfficeAuditRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, parent_id=Contract_obj)
                three_appave = Company.objects.get(id=23).head_people
                LogisticsOfficeAuditRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, parent_id=Contract_obj)
                four_appave = Contract_obj.company.leaders_id
                LogisticsOfficeAuditRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, parent_id=Contract_obj)

                if float(Contract_obj.total_money.replace(",", "")) < 10000:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Company.objects.get(id=23).leaders_id, parent_id=Contract_obj)
                elif 1000 <= float(Contract_obj.total_money.replace(",", "")) < 200000:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=Contract_obj)
                else:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit',audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), parent_id=Contract_obj)

                try:
                    cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                except:
                    returnDict = {'code': 500, 'message': '系统未设置 ”财务支付“ 一职，请联系管理员设置'}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                LogisticsOfficeAuditRecord.objects.create(node='six', state='unaudit', audit_people=cn_obj, parent_id=Contract_obj)
                Contract_obj.state = state
                Contract_obj.save()

            elif state == 'one' or state == 'eight':
                if state == 'one' and not Contract_obj.logisticsofficeauditrecord_set.filter(node='one'):
                    returnDict = {'message': '申请人为科室负责人，无法退回到该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Contract_obj.current_audit_users.clear()
                if state == 'one':
                    Contract_obj.logisticsofficeauditrecord_set.filter(node__in=['one', 'two', 'three', 'four', 'five', 'six']).delete()
                    LogisticsOfficeAuditRecord.objects.create(node='one', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Contract_obj)
                    Contract_obj.current_audit_users.add(audit_people_objs.first())
                else:
                    Contract_obj.current_audit_users.add(Contract_obj.apply_user)
                    Contract_obj.logisticsofficeauditrecord_set.all().delete()
                    if Contract_obj.logisticsofficeauditrecord_set.filter(node='zero'):
                        try:
                            htkj_obj = Staffing.objects.get(station='合同付款会计').post_personnel.all()
                        except:
                            returnDict = {'code': 500, 'message': '系统未设置 ”合同付款会计“ 一职，请联系管理员设置'}
                            return HttpResponse(json.dumps(returnDict), content_type="application/json")

                        for htkj in htkj_obj:
                            LogisticsOfficeAuditRecord.objects.create(node='zero', state='unaudit', audit_people=htkj, parent_id=Contract_obj)

                    one_appave = Contract_obj.company.head_people
                    if one_appave != Contract_obj.apply_user:
                        LogisticsOfficeAuditRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, parent_id=Contract_obj)
                two_appave = Company.objects.get(id=22).head_people
                LogisticsOfficeAuditRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, parent_id=Contract_obj)
                three_appave = Company.objects.get(id=23).head_people
                LogisticsOfficeAuditRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, parent_id=Contract_obj)
                four_appave = Contract_obj.company.leaders_id
                LogisticsOfficeAuditRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, parent_id=Contract_obj)
                if float(Contract_obj.total_money.replace(",", "")) < 10000:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Company.objects.get(id=23).leaders_id, parent_id=Contract_obj)
                elif 1000 <= float(Contract_obj.total_money.replace(",", "")) < 200000:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=Contract_obj)
                else:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit',audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), parent_id=Contract_obj)
                try:
                    cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                except:
                    returnDict = {'code': 500, 'message': '系统未设置 ”财务支付“ 一职，请联系管理员设置'}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                LogisticsOfficeAuditRecord.objects.create(node='six', state='unaudit', audit_people=cn_obj, parent_id=Contract_obj)
                Contract_obj.state = state
                Contract_obj.save()

            elif state == 'two':
                Contract_obj.current_audit_users.clear()
                Contract_obj.logisticsofficeauditrecord_set.filter(node__in=['two', 'three', 'four', 'five', 'six']).delete()
                LogisticsOfficeAuditRecord.objects.create(node='two', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Contract_obj)
                Contract_obj.current_audit_users.add(audit_people_objs.first())
                three_appave = Company.objects.get(id=23).head_people
                LogisticsOfficeAuditRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, parent_id=Contract_obj)
                four_appave = Contract_obj.company.leaders_id
                LogisticsOfficeAuditRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, parent_id=Contract_obj)
                if float(Contract_obj.total_money.replace(",", "")) < 10000:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Company.objects.get(id=23).leaders_id, parent_id=Contract_obj)
                elif 1000 <= float(Contract_obj.total_money.replace(",", "")) < 200000:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=Contract_obj)
                else:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), parent_id=Contract_obj)
                try:
                    cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                except:
                    returnDict = {'code': 500, 'message': '系统未设置 ”财务支付“ 一职，请联系管理员设置'}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                LogisticsOfficeAuditRecord.objects.create(node='six', state='unaudit', audit_people=cn_obj, parent_id=Contract_obj)
                Contract_obj.state = state
                Contract_obj.save()

            elif state == 'three':
                Contract_obj.current_audit_users.clear()
                Contract_obj.logisticsofficeauditrecord_set.filter(node__in=['three', 'four', 'five', 'six']).delete()
                LogisticsOfficeAuditRecord.objects.create(node='three', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Contract_obj)
                Contract_obj.current_audit_users.add(audit_people_objs.first())
                four_appave = Contract_obj.company.leaders_id
                LogisticsOfficeAuditRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, parent_id=Contract_obj)
                if float(Contract_obj.total_money.replace(",", "")) < 10000:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Company.objects.get(id=23).leaders_id, parent_id=Contract_obj)
                elif 1000 <= float(Contract_obj.total_money.replace(",", "")) < 200000:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=Contract_obj)
                else:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), parent_id=Contract_obj)
                try:
                    cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                except:
                    returnDict = {'code': 500, 'message': '系统未设置 ”财务支付“ 一职，请联系管理员设置'}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                LogisticsOfficeAuditRecord.objects.create(node='six', state='unaudit', audit_people=cn_obj, parent_id=Contract_obj)
                Contract_obj.state = state
                Contract_obj.save()

            elif state == 'four':
                Contract_obj.current_audit_users.clear()
                Contract_obj.logisticsofficeauditrecord_set.filter(node__in=['four', 'five', 'six']).delete()
                LogisticsOfficeAuditRecord.objects.create(node='four', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Contract_obj)
                Contract_obj.current_audit_users.add(audit_people_objs.first())
                if float(Contract_obj.total_money.replace(",", "")) < 10000:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Company.objects.get(id=23).leaders_id, parent_id=Contract_obj)
                elif 1000 <= float(Contract_obj.total_money.replace(",", "")) < 200000:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=Contract_obj)
                else:
                    LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), parent_id=Contract_obj)
                try:
                    cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                except:
                    returnDict = {'code': 500, 'message': '系统未设置 ”财务支付“ 一职，请联系管理员设置'}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                LogisticsOfficeAuditRecord.objects.create(node='six', state='unaudit', audit_people=cn_obj, parent_id=Contract_obj)
                Contract_obj.state = state
                Contract_obj.save()

            elif state == 'five':
                Contract_obj.current_audit_users.clear()
                Contract_obj.logisticsofficeauditrecord_set.filter(node__in=['five', 'six']).delete()
                LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Contract_obj)
                Contract_obj.current_audit_users.add(audit_people_objs.first())
                try:
                    cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                except:
                    returnDict = {'code': 500, 'message': '系统未设置 ”财务支付“ 一职，请联系管理员设置'}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                LogisticsOfficeAuditRecord.objects.create(node='six', state='unaudit', audit_people=cn_obj, parent_id=Contract_obj)
                Contract_obj.state = state
                Contract_obj.save()

            else:
                Contract_obj.current_audit_users.clear()
                Contract_obj.logisticsofficeauditrecord_set.filter(node__in=['six']).delete()
                LogisticsOfficeAuditRecord.objects.create(node='six', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Contract_obj)
                Contract_obj.current_audit_users.add(audit_people_objs.first())
                Contract_obj.state = state
                Contract_obj.save()

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 餐补付款列表页
class MealPaymentList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/MealPaymentList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = NutritionalMeals.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data) | Q(title__contains=search_data),
                                          state__in=['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'stop']).order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'title': obj.title,
             'apply_user': obj.apply_user.real_name,
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'type': obj.get_type_display(),
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'total_amount': obj.total_amount,
             'source': obj.source,
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 餐补付款详情页
class MealPaymentDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = NutritionalMeals.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.nutritionalmealsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.nutritionalmealsauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        returndata = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in returndata:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)
        leaders_list = User.objects.filter(group__id=2)
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic,
                   "is_edit": "true",
                   "detail_pay": json.loads(json.loads(obj.detail_pay)),
                   "company_list": company_list, "leaders_list": leaders_list, 'revise': revise,
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                   "flow_dict": flow_dict
                   }
        return render(request, "back_management/MealPaymentDetail.html", context)

    def post(self, request):
        MealId = request.POST.get('MealId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Meal_obj = NutritionalMeals.objects.get(id=MealId)
        if types == 'delete':
            Meal_obj.nutritionalmealsauditrecord_set.all().delete()  # 清除审批列表
            Meal_obj.current_audit_users.clear()  # 清除当前审批
            Meal_obj.audit_users_already.clear()  # 清除已审批列表
            Meal_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人
            cwk_obj = Company.objects.get(id=23)
            rsk_obj = Company.objects.get(id=16)
            try:
                gh_obj = Staffing.objects.get(station='工会主席').post_personnel.all().first()
            except Exception as e:
                returnDict = {'code': 500, 'message': '工会主席岗位未维护，请联系管理员维护'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            try:
                yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
            except Exception as e:
                returnDict = {'code': 500, 'message': '院长岗位未维护，请联系管理员维护'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            try:
                sj_obj = Staffing.objects.get(station='书记').post_personnel.all().first()
            except Exception as e:
                returnDict = {'code': 500, 'message': '书记岗位未维护，请联系管理员维护'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            try:
                cwzf_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
            except Exception as e:
                returnDict = {'code': 500, 'message': '财务支付岗位未维护，请联系管理员维护'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            if state == "one" or state == 'eight':
                if state == "one" and not Meal_obj.nutritionalmealsauditrecord_set.filter(node='one'):
                    returnDict = {'message': '申请人为科室负责人，无法退回到该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

                four_appave = Meal_obj.nutritionalmealsauditrecord_set.filter(node='four').first().audit_people
                Meal_obj.nutritionalmealsauditrecord_set.all().delete()
                Meal_obj.current_audit_users.clear()
                three_appave = cwk_obj.head_people
                if Meal_obj.type == 'two':
                    NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='one')
                    if state == "one":
                        Meal_obj.current_audit_users.add(audit_people_objs.first())
                    else:
                        Meal_obj.current_audit_users.add(Meal_obj.apply_user)
                    Meal_obj.state = state
                    # 人事科审核
                    two_appave = rsk_obj.head_people
                    NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=two_appave, audit_note='', state='unaudit', node='two')
                    # 财务科审核
                    NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=three_appave, audit_note='', state='unaudit', node='three')
                    # 申请人分管领导
                    four_appave = Meal_obj.company.leaders_id
                    NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=four_appave, audit_note='', state='unaudit', node='four')
                else:
                    NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='one')
                    Meal_obj.current_audit_users.add(audit_people_objs.first())
                    Meal_obj.state = state
                    # 财务科审核
                    NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=three_appave, audit_note='', state='unaudit', node='three')
                    # 选择的分管领导
                    NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=four_appave, audit_note='', state='unaudit', node='four')

                total_amount = float(Meal_obj.total_amount.replace(",", ""))
                five_appave = gh_obj if total_amount <= 10000 else yz_obj if 10000 < total_amount < 200000 else sj_obj
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=five_appave, audit_note='', state='unaudit', node='five')
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')
                Meal_obj.save()

            elif state == "two":
                if not Meal_obj.nutritionalmealsauditrecord_set.filter(node='two'):
                    returnDict = {'message': '该付款类型无需人事科审核，无法退回到该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

                Meal_obj.nutritionalmealsauditrecord_set.filter(node__in=["two", "three", "four", "five", "six"]).delete()
                Meal_obj.current_audit_users.clear()

                three_appave = cwk_obj.head_people
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='two')
                Meal_obj.current_audit_users.add(audit_people_objs.first())
                Meal_obj.state = state

                # 财务科审核
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=three_appave, audit_note='', state='unaudit', node='three')
                # 申请人分管领导
                four_appave = Meal_obj.company.leaders_id
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=four_appave, audit_note='', state='unaudit', node='four')


                total_amount = float(Meal_obj.total_amount.replace(",", ""))
                five_appave = gh_obj if total_amount <= 10000 else yz_obj if 10000 < total_amount < 200000 else sj_obj
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=five_appave, audit_note='', state='unaudit', node='five')
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')
                Meal_obj.save()

            elif state == "three":
                four_appave = Meal_obj.nutritionalmealsauditrecord_set.filter(node='four').first().audit_people
                Meal_obj.nutritionalmealsauditrecord_set.filter(node__in=["three", "four", "five", "six"]).delete()
                Meal_obj.current_audit_users.clear()
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='three')
                Meal_obj.current_audit_users.add(audit_people_objs.first())
                Meal_obj.state = state
                # 申请人分管领导
                if Meal_obj.type == 'two':
                    four_appave = Meal_obj.company.leaders_id
                    NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=four_appave, audit_note='', state='unaudit', node='four')
                else:
                    NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=four_appave, audit_note='', state='unaudit', node='four')
                total_amount = float(Meal_obj.total_amount.replace(",", ""))
                five_appave = gh_obj if total_amount <= 10000 else yz_obj if 10000 < total_amount < 200000 else sj_obj
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=five_appave, audit_note='', state='unaudit', node='five')
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')
                Meal_obj.save()

            elif state == "four":
                Meal_obj.nutritionalmealsauditrecord_set.filter(node__in=["four", "five", "six"]).delete()
                Meal_obj.current_audit_users.clear()
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='four')
                Meal_obj.current_audit_users.add(audit_people_objs.first())
                Meal_obj.state = state
                total_amount = float(Meal_obj.total_amount.replace(",", ""))
                five_appave = gh_obj if total_amount <= 10000 else yz_obj if 10000 < total_amount < 200000 else sj_obj
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=five_appave, audit_note='', state='unaudit', node='five')
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')
                Meal_obj.save()

            elif state == "five":
                Meal_obj.nutritionalmealsauditrecord_set.filter(node__in=["five", "six"]).delete()
                Meal_obj.current_audit_users.clear()

                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='five')
                Meal_obj.current_audit_users.add(audit_people_objs.first())
                Meal_obj.state = state
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')
                Meal_obj.save()

            else:
                Meal_obj.nutritionalmealsauditrecord_set.filter(node__in=["six"]).delete()
                Meal_obj.current_audit_users.clear()
                NutritionalMealsAuditRecord.objects.create(parent_id=Meal_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='six')
                Meal_obj.current_audit_users.add(audit_people_objs.first())
                Meal_obj.state = state
                Meal_obj.save()
            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 新增医疗服务项目审批列表页
class NewMedicalTreatmentList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/NewMedicalTreatmentList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = NewMedicalServices.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data) | Q(title__contains=search_data) | Q(number__contains=search_data),
                                          state__in=['one', 'two', 'three', 'four', 'five', 'seven', 'eight', 'stop']).order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'number': obj.number,
             'title': obj.title,
             "url": "new_medical_services_draft_view?id=" + str(
                 obj.id) if obj.state == 'draft' else "new_medical_services_detail_view?id=" + str(obj.id),
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 新增医疗服务项目审批详情页
class NewMedicalTreatmentDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = NewMedicalServices.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.newmedicalservicesauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        one_step = obj.newmedicalservicesauditrecord_set.filter(node__in=['one', 'two'])
        if one_step:
            apply_people = []
            apply = 'true'
            for obj_s in one_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['one'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                'sear': len([i for i in flow_dict]) + 1}

        two_step = obj.newmedicalservicesauditrecord_set.filter(node='three')
        if two_step:
            apply_people = []
            apply = 'true'
            for obj_s in two_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['two'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                'sear': len([i for i in flow_dict]) + 1}

        three_step = obj.newmedicalservicesauditrecord_set.filter(node='four')
        if three_step:
            apply_people = []
            apply = 'true'
            for obj_s in three_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['three'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                  'sear': len([i for i in flow_dict]) + 1}

        four_step = obj.newmedicalservicesauditrecord_set.filter(node='five')
        if four_step:
            apply_people = []
            apply = 'true'
            for obj_s in four_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['four'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                 'sear': len([i for i in flow_dict]) + 1}

        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic,
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number)[0].pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                   "flow_dict": flow_dict}
        return render(request, "back_management/NewMedicalTreatmentDetail.html", context)

    def post(self, request):
        NewMedicalId = request.POST.get('NewMedicalId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        NewMedical_obj = NewMedicalServices.objects.get(id=NewMedicalId)
        if types == 'delete':
            NewMedical_obj.newmedicalservicesauditrecord_set.all().delete()  # 清除审批列表
            NewMedical_obj.current_audit_users.clear()  # 清除当前审批
            NewMedical_obj.audit_users_already.clear()  # 清除已审批列表
            NewMedical_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人
            if not audit_people_objs.count():
                returnDict = {'message': '请选择审核人！', "code": 400}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            sjk = Company.objects.get(id=22)
            ywk = Company.objects.get(id=13)
            hlb = Company.objects.get(id=15)
            if state == "one" or state == 'eight':
                NewMedical_obj.newmedicalservicesauditrecord_set.all().delete()
                NewMedical_obj.current_audit_users.clear()
                if state == "one":
                    NewMedicalServicesAuditRecord.objects.create(parent_id=NewMedical_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='one')
                    NewMedical_obj.current_audit_users.add(audit_people_objs.first())
                else:
                    if request.user.group.id == 4:
                        one_appave = ywk.head_people
                        NewMedicalServicesAuditRecord.objects.create(parent_id=NewMedical_obj, audit_people=one_appave, audit_note='', state='unaudit', node='one')
                    if request.user.group.id == 5:
                        one_appave = hlb.head_people
                        NewMedicalServicesAuditRecord.objects.create(parent_id=NewMedical_obj, audit_people=one_appave, audit_note='', state='unaudit', node='one')
                    NewMedical_obj.current_audit_users.add(NewMedical_obj.apply_user)
                NewMedicalServicesAuditRecord.objects.create(parent_id=NewMedical_obj, audit_people=sjk.head_people, audit_note='', state='unaudit', node='three')
                NewMedicalServicesAuditRecord.objects.create(parent_id=NewMedical_obj, audit_people=NewMedical_obj.company.leaders_id, audit_note='', state='unaudit', node='four')

            if state == "three":
                NewMedical_obj.newmedicalservicesauditrecord_set.filter(node__in=["three", 'four']).delete()
                NewMedical_obj.current_audit_users.clear()
                NewMedicalServicesAuditRecord.objects.create(parent_id=NewMedical_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='three')
                NewMedical_obj.current_audit_users.add(audit_people_objs.first())
                NewMedicalServicesAuditRecord.objects.create(parent_id=NewMedical_obj, audit_people=NewMedical_obj.company.leaders_id, audit_note='', state='unaudit', node='four')

            else:
                NewMedical_obj.newmedicalservicesauditrecord_set.filter(node__in=['four']).delete()
                NewMedical_obj.current_audit_users.clear()
                NewMedicalServicesAuditRecord.objects.create(parent_id=NewMedical_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='four')
                NewMedical_obj.current_audit_users.add(audit_people_objs.first())

            NewMedical_obj.state = state
            NewMedical_obj.save()

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 手术分级分权列表页
class SurgicalClassificationList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/SurgicalClassificationList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = SurgicalGrading.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data) | Q(reason__contains=search_data), state__in=['one', 'two', 'three', 'seven', 'eight', 'stop']).order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'current_surgical_level': obj.current_surgical_level,
             'apply_surgical_level': obj.apply_surgical_level,
             'reason': obj.reason,
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 手术分级分权详情页
class SurgicalClassificationDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = SurgicalGrading.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.surgicalgradingauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.surgicalgradingauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic,
                   "flow_dict": flow_dict,
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, "back_management/SurgicalClassificationDetail.html", context)

    def post(self, request):
        SurgicalId = request.POST.get('SurgicalId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Surgical_obj = SurgicalGrading.objects.get(id=SurgicalId)
        if types == 'delete':
            Surgical_obj.surgicalgradingauditrecord_set.all().delete()  # 清除审批列表
            Surgical_obj.current_audit_users.clear()  # 清除当前审批
            Surgical_obj.audit_users_already.clear()  # 清除已审批列表
            Surgical_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人
            if not audit_people_objs.count():
                returnDict = {'message': '请选择审核人！', "code": 400}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            ywk = Company.objects.get(id=13)
            try:
                yyh_obj = Staffing.objects.get(station='医疗技术临床应用管理委员会').post_personnel.all().first()
            except Exception as e:
                print(e)
                returnDict = {'code': 500, 'message': '医疗技术临床应用管理委员会负责人岗位未维护，请联系管理员维护'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            if state == 'one':
                if Surgical_obj.surgicalgradingauditrecord_set.filter(node="one"):
                    returnDict = {'message': '申请人为科室负责人，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Surgical_obj.surgicalgradingauditrecord_set.all().delete()  # 清除审批列表
                Surgical_obj.current_audit_users.clear()
                SurgicalGradingAuditRecord.objects.create(parent_id=Surgical_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='one')
                Surgical_obj.current_audit_users.add(audit_people_objs.first())
                two_setp = ywk.head_people
                SurgicalGradingAuditRecord.objects.create(parent_id=Surgical_obj, audit_people=two_setp, audit_note='', state='unaudit', node='two')
                SurgicalGradingAuditRecord.objects.create(parent_id=Surgical_obj, audit_people=yyh_obj, audit_note='', state='unaudit', node='three')

            elif state == 'two':
                Surgical_obj.surgicalgradingauditrecord_set.filter(node__in=['two', 'three']).delete()  # 清除审批列表
                Surgical_obj.current_audit_users.clear()

                SurgicalGradingAuditRecord.objects.create(parent_id=Surgical_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='two')
                Surgical_obj.current_audit_users.add(audit_people_objs.first())
                SurgicalGradingAuditRecord.objects.create(parent_id=Surgical_obj, audit_people=yyh_obj, audit_note='', state='unaudit', node='three')

            elif state == 'three':
                Surgical_obj.surgicalgradingauditrecord_set.filter(node__in=['three']).delete()  # 清除审批列表
                Surgical_obj.current_audit_users.clear()
                SurgicalGradingAuditRecord.objects.create(parent_id=Surgical_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='three')
                Surgical_obj.current_audit_users.add(audit_people_objs.first())

            else:
                Surgical_obj.surgicalgradingauditrecord_set.all().delete()  # 清除审批列表
                Surgical_obj.current_audit_users.clear()
                Surgical_obj.current_audit_users.add(Surgical_obj.apply_user)
                one_setp = Surgical_obj.company.head_people
                if Surgical_obj.apply_user != one_setp:
                    SurgicalGradingAuditRecord.objects.create(parent_id=Surgical_obj, audit_people=one_setp, audit_note='', state='unaudit', node='one')
                two_setp = ywk.head_people
                SurgicalGradingAuditRecord.objects.create(parent_id=Surgical_obj, audit_people=two_setp, audit_note='', state='unaudit', node='two')
                SurgicalGradingAuditRecord.objects.create(parent_id=Surgical_obj, audit_people=yyh_obj, audit_note='', state='unaudit', node='three')
            Surgical_obj.state = state
            Surgical_obj.save()
            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 临床医师单独执业资格列表页
class PracticingQualificationList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/PracticingQualificationList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = SoloPracticeApply.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data), state__in=['one', 'two', 'seven', 'eight', 'stop']).order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'university': obj.university,
             'subject': obj.subject,
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 临床医师单独执业资格详情页
class PracticingQualificationDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = SoloPracticeApply.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.solopracticeapplyauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.solopracticeapplyauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic,
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number)[0].pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                   "flow_dict": flow_dict}
        return render(request, "back_management/PracticingQualificationDetail.html", context)

    def post(self, request):
        PracticingId = request.POST.get('PracticingId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Practicing_obj = SoloPracticeApply.objects.get(id=PracticingId)
        if types == 'delete':
            Practicing_obj.solopracticeapplyauditrecord_set.all().delete()  # 清除审批列表
            Practicing_obj.current_audit_users.clear()  # 清除当前审批
            Practicing_obj.audit_users_already.clear()  # 清除已审批列表
            Practicing_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人
            if not audit_people_objs.count():
                returnDict = {'message': '请选择审核人！', "code": 400}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            ywk = Company.objects.get(id=13)

            if state == 'one':
                if not Practicing_obj.solopracticeapplyauditrecord_set.filter(node="one"):
                    returnDict = {'message': '申请人为科室负责人，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Practicing_obj.solopracticeapplyauditrecord_set.all().delete()  # 清除审批列表
                Practicing_obj.current_audit_users.clear()
                SoloPracticeApplyAuditRecord.objects.create(parent_id=Practicing_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='one')
                Practicing_obj.current_audit_users.add(audit_people_objs.first())
                two_setp = ywk.head_people
                SoloPracticeApplyAuditRecord.objects.create(parent_id=Practicing_obj, audit_people=two_setp, audit_note='', state='unaudit', node='two')

            elif state == 'two':
                Practicing_obj.solopracticeapplyauditrecord_set.filter(node__in=['two']).delete()  # 清除审批列表
                Practicing_obj.current_audit_users.clear()
                SoloPracticeApplyAuditRecord.objects.create(parent_id=Practicing_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='two')
                Practicing_obj.current_audit_users.add(audit_people_objs.first())

            else:
                Practicing_obj.solopracticeapplyauditrecord_set.all().delete()  # 清除审批列表
                Practicing_obj.current_audit_users.clear()
                Practicing_obj.current_audit_users.add(Practicing_obj.apply_user)
                one_setp = Practicing_obj.company.head_people
                if Practicing_obj.apply_user != one_setp:
                    SoloPracticeApplyAuditRecord.objects.create(parent_id=Practicing_obj, audit_people=one_setp, audit_note='', state='unaudit', node='one')
                two_setp = ywk.head_people
                SoloPracticeApplyAuditRecord.objects.create(parent_id=Practicing_obj, audit_people=two_setp, audit_note='', state='unaudit', node='two')
            Practicing_obj.state = state
            Practicing_obj.save()
            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 中层干部外出列表页
class MiddleLevelList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/MiddleLevelList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = OutgoingCadresData.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data) | Q(title__contains=search_data), state__in=['one', 'two', 'three', 'four', 'seven', 'eight', 'stop']).order_by('-create_time')
        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name,
             'outgoing_person': ", ".join([i.real_name for i in obj.outgoing_person.all()]),
             'start_time': obj.start_time, 'end_time': obj.end_time, 'title': obj.title,
             'company': obj.company.name, 'state': obj.get_state_str(),
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()])}
            for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 中层干部外出详情页
class MiddleLevelDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        outgoing_id = request.GET.get("id", None)
        outgoing_obj = OutgoingCadresData.objects.get(id=int(outgoing_id))
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=outgoing_obj.uuid)]

        audit_dic, flow_dict = {}, {}
        for audit_obj in outgoing_obj.outgoingcadresdatarecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in outgoing_obj.outgoingcadresdatarecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   'apply': outgoing_obj.apply_user.real_name,
                   "company": outgoing_obj.company.name, 'uuid': outgoing_obj.uuid, 'file_list': file_list,
                   'obj': outgoing_obj, "audit_dic": audit_dic, "flow_dict": flow_dict,
                   "file_path": Topicsattachments.objects.filter(topics_number=outgoing_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=outgoing_obj.uuid) else ""}
        return render(request, "back_management/MiddleLevelDetail.html", context)

    def post(self, request):
        MiddleId = request.POST.get('MiddleId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Middle_obj = OutgoingCadresData.objects.get(id=MiddleId)
        if types == 'delete':
            Middle_obj.outgoingcadresdatarecord_set.all().delete()  # 清除审批列表
            Middle_obj.current_audit_users.clear()  # 清除当前审批
            Middle_obj.audit_users_already.clear()  # 清除已审批列表
            Middle_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人
            if not audit_people_objs.count():
                returnDict = {'message': '请选择审核人！', "code": 400}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            if state == 'one' or state == 'eight':
                if state == 'one':
                    if not Middle_obj.outgoingcadresdatarecord_set.filter(node="one"):
                        returnDict = {'message': '无法退回该节点！', "code": 400}
                        return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Middle_obj.outgoingcadresdatarecord_set.all().delete()  # 清除审批列表
                Middle_obj.current_audit_users.clear()
                Middle_obj.audit_users_already.clear()

                if state == 'one':
                    OutgoingCadresDataRecord.objects.create(parent_id=Middle_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='one')
                    Middle_obj.current_audit_users.add(audit_people_objs.first())
                    Middle_obj.state = "one"
                else:
                    Middle_obj.state = "eight"
                    Middle_obj.current_audit_users.add(Middle_obj.apply_user)
                    if Middle_obj.outgoingcadresdatarecord_set.filter(node="one"):
                        OutgoingCadresDataRecord.objects.create(parent_id=Middle_obj, audit_people=Middle_obj.department_charge.head_people, audit_note='', state='unaudit', node='one')

                OutgoingCadresDataRecord.objects.create(parent_id=Middle_obj, audit_people=Middle_obj.company.leaders_id, audit_note='', state='unaudit', node='two')
                four_prave = Company.objects.get(id=3).head_people
                OutgoingCadresDataRecord.objects.create(node='four', parent_id=Middle_obj, audit_people=four_prave)
                OutgoingCadresDataRecord.objects.create(node='three', parent_id=Middle_obj, audit_people=Staffing.objects.get(station='外出干部审核员').post_personnel.all().first())

            elif state == 'two':
                if Middle_obj.state in ["one"]:
                    returnDict = {'message': '无法退回还未到达节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Middle_obj.state = "two"
                Middle_obj.current_audit_users.clear()
                Middle_obj.outgoingcadresdatarecord_set.filter(node__in=['two', 'three', 'four']).delete()  # 清除审批列表
                OutgoingCadresDataRecord.objects.create(parent_id=Middle_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='two')
                Middle_obj.current_audit_users.add(audit_people_objs.first())
                four_prave = Company.objects.get(id=3).head_people
                OutgoingCadresDataRecord.objects.create(node='four', parent_id=Middle_obj, audit_people=four_prave)
                OutgoingCadresDataRecord.objects.create(node='three', parent_id=Middle_obj, audit_people=Staffing.objects.get(station='外出干部审核员').post_personnel.all().first())

            elif state == 'four':
                if Middle_obj.state in ["one", "two"]:
                    returnDict = {'message': '无法退回还未到达节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Middle_obj.state = "four"
                Middle_obj.current_audit_users.clear()
                Middle_obj.outgoingcadresdatarecord_set.filter(node__in=['three', 'four']).delete()  # 清除审批列表
                OutgoingCadresDataRecord.objects.create(parent_id=Middle_obj, audit_people=audit_people_objs.first(), audit_note='', state='unaudit', node='four')
                Middle_obj.current_audit_users.add(audit_people_objs.first())
                OutgoingCadresDataRecord.objects.create(node='three', parent_id=Middle_obj, audit_people=Staffing.objects.get(station='外出干部审核员').post_personnel.all().first())

            else:
                if Middle_obj.state in ["one", "two", "four"]:
                    returnDict = {'message': '无法退回还未到达节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Middle_obj.state = "three"
                Middle_obj.current_audit_users.clear()
                Middle_obj.outgoingcadresdatarecord_set.filter(node__in=['three']).delete()  # 清除审批列表
                Middle_obj.current_audit_users.add(audit_people_objs.first())
                OutgoingCadresDataRecord.objects.create(node='three', parent_id=Middle_obj, audit_people=audit_people_objs.first())

            Middle_obj.save()
            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 请假列表
class LeaveApplicationList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/LeaveApplicationList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = LeaveRequest.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data) | Q(reason__contains=search_data), state__in=['one', 'two', 'three', 'four', 'seven', 'eight', 'stop']).order_by('-create_time')
        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name,
             'leave_type': obj.get_leave_type(),
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"), 'title': obj.reason,
             'company': obj.company.name, 'state': obj.get_str_state(),
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()])}
            for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 请假详情&退回&删除
class LeaveApplicationdetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        id = request.GET.get("id", None)
        obj = LeaveRequest.objects.get(id=id)
        leave_li = [
            {'value': 'a', 'leave': '年休假'},
            {'value': 'b', 'leave': '婚假'},
            {'value': 'c', 'leave': '丧假'},
            {'value': 'd', 'leave': '事假'},
            {'value': 'e', 'leave': '病假'},
            {'value': 'f', 'leave': '探亲假'},
            {'value': 'g', 'leave': '放射假'},
            {'value': 'h', 'leave': '产假'},
        ]
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.leaverequestauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.leaverequestauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   "leave_type": obj.get_leave_type(),
                   'user_obj': User.objects.filter(group_id=1),
                   "leave_li": leave_li, "flow_dict": flow_dict, "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, "back_management/LeaveApplicationdetail.html", context)

    def post(self, request):
        LeaveId = request.POST.get('LeaveId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Leave_obj = LeaveRequest.objects.get(id=LeaveId)
        if types == 'delete':
            Leave_obj.leaverequestauditrecord_set.all().delete()  # 清除审批列表
            Leave_obj.current_audit_users.clear()  # 清除当前审批
            Leave_obj.audit_users_already.clear()  # 清除已审批列表
            Leave_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人

            if state == "one":
                if not Leave_obj.leaverequestauditrecord_set.filter(node="one"):
                    returnDict = {'message': '申请人为科室负责人，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Leave_obj.leaverequestauditrecord_set.filter(node="one").all().delete()
                LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=audit_people_objs.first(), node='one', state='unaudit', audit_note='')
                Leave_obj.current_audit_users.clear()
                Leave_obj.audit_users_already.clear()
                Leave_obj.state = 'one'
                Leave_obj.save()
                Leave_obj.current_audit_users.add(audit_people_objs.first())

                if Leave_obj.leaverequestauditrecord_set.filter(node="two"):
                    two_step = Leave_obj.leaverequestauditrecord_set.filter(node="two").last()
                    two_appave = two_step.audit_people
                    Leave_obj.leaverequestauditrecord_set.filter(node="two").all().delete()
                    LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=two_appave, node='two', state='unaudit', audit_note='')

                if Leave_obj.leaverequestauditrecord_set.filter(node="three"):
                    three_step = Leave_obj.leaverequestauditrecord_set.filter(node="three").last()
                    three_appave = three_step.audit_people
                    Leave_obj.leaverequestauditrecord_set.filter(node="three").all().delete()
                    LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=three_appave, node='three', state='unaudit', audit_note='')

                if Leave_obj.leaverequestauditrecord_set.filter(node="four"):
                    four_step = Leave_obj.leaverequestauditrecord_set.filter(node="four").last()
                    four_appave = four_step.audit_people
                    Leave_obj.leaverequestauditrecord_set.filter(node="four").all().delete()
                    LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=four_appave, node='four', state='unaudit', audit_note='')

            elif state == "two":
                if not Leave_obj.leaverequestauditrecord_set.filter(node="two"):
                    returnDict = {'message': '申请人无需报备，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

                Leave_obj.leaverequestauditrecord_set.filter(node="two").all().delete()
                LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=audit_people_objs.first(), node='two', state='unaudit', audit_note='')
                Leave_obj.current_audit_users.clear()
                Leave_obj.audit_users_already.clear()
                Leave_obj.state = 'two'
                Leave_obj.save()
                Leave_obj.current_audit_users.add(audit_people_objs.first())

                if Leave_obj.leaverequestauditrecord_set.filter(node="three"):
                    three_step = Leave_obj.leaverequestauditrecord_set.filter(node="three").last()
                    three_appave = three_step.audit_people
                    Leave_obj.leaverequestauditrecord_set.filter(node="three").all().delete()
                    LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=three_appave, node='three', state='unaudit', audit_note='')

                if Leave_obj.leaverequestauditrecord_set.filter(node="four"):
                    four_step = Leave_obj.leaverequestauditrecord_set.filter(node="four").last()
                    four_appave = four_step.audit_people
                    Leave_obj.leaverequestauditrecord_set.filter(node="four").all().delete()
                    LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=four_appave, node='four', state='unaudit', audit_note='')

            elif state == "three":
                if not Leave_obj.leaverequestauditrecord_set.filter(node="three"):
                    returnDict = {'message': '无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

                Leave_obj.leaverequestauditrecord_set.filter(node="three").all().delete()
                LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=audit_people_objs.first(), node='three', state='unaudit', audit_note='')
                Leave_obj.current_audit_users.clear()
                Leave_obj.audit_users_already.clear()
                Leave_obj.state = 'three'
                Leave_obj.save()
                Leave_obj.current_audit_users.add(audit_people_objs.first())

                if Leave_obj.leaverequestauditrecord_set.filter(node="four"):
                    four_step = Leave_obj.leaverequestauditrecord_set.filter(node="four").last()
                    four_appave = four_step.audit_people
                    Leave_obj.leaverequestauditrecord_set.filter(node="four").all().delete()
                    LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=four_appave, node='four', state='unaudit', audit_note='')

            elif state == "four":
                if not Leave_obj.leaverequestauditrecord_set.filter(node="four"):
                    returnDict = {'message': '无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

                Leave_obj.leaverequestauditrecord_set.filter(node="four").all().delete()
                LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=audit_people_objs.first(), node='four', state='unaudit', audit_note='')
                Leave_obj.current_audit_users.clear()
                Leave_obj.audit_users_already.clear()
                Leave_obj.state = 'four'
                Leave_obj.save()
                Leave_obj.current_audit_users.add(audit_people_objs.first())

            else:
                Leave_obj.current_audit_users.clear()
                Leave_obj.audit_users_already.clear()
                Leave_obj.state = "eight"
                Leave_obj.save()
                Leave_obj.current_audit_users.add(Leave_obj.apply_user)
                if Leave_obj.leaverequestauditrecord_set.filter(node="one"):
                    one_step = Leave_obj.leaverequestauditrecord_set.filter(node="one").last()
                    one_appave = one_step.audit_people
                    Leave_obj.leaverequestauditrecord_set.filter(node="one").all().delete()
                    LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=one_appave, node='one', state='unaudit', audit_note='')

                if Leave_obj.leaverequestauditrecord_set.filter(node="two"):
                    two_step = Leave_obj.leaverequestauditrecord_set.filter(node="two").last()
                    two_appave = two_step.audit_people
                    Leave_obj.leaverequestauditrecord_set.filter(node="two").all().delete()
                    LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=two_appave, node='two', state='unaudit', audit_note='')

                if Leave_obj.leaverequestauditrecord_set.filter(node="three"):
                    three_step = Leave_obj.leaverequestauditrecord_set.filter(node="three").last()
                    three_appave = three_step.audit_people
                    Leave_obj.leaverequestauditrecord_set.filter(node="three").all().delete()
                    LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=three_appave, node='three', state='unaudit', audit_note='')

                if Leave_obj.leaverequestauditrecord_set.filter(node="four"):
                    four_step = Leave_obj.leaverequestauditrecord_set.filter(node="four").last()
                    four_appave = four_step.audit_people
                    Leave_obj.leaverequestauditrecord_set.filter(node="four").all().delete()
                    LeaveRequestAuditRecord.objects.create(parent_id=Leave_obj, audit_people=four_appave, node='four', state='unaudit', audit_note='')

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 离职申请列表页
class ResignationApplicationList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/ResignationApplicationList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = Dimission.objects.filter(Q(user__real_name__contains=search_data) | Q(company__name__contains=search_data) | Q(dimission_note__contains=search_data)).order_by('-create_time')
        data_list = [
            {'id': obj.id, 'apply_user': obj.user.real_name,
             'dimission_note': obj.dimission_note,
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'company': obj.company.name, 'state': obj.get_state_str(),
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()])}
            for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 离职申请详情页
class ResignationApplicationDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get("id", None)
        obj = Dimission.objects.get(id=id)
        audit_dic, flow_dict, five_node_list = {}, {}, []
        for audit_obj in obj.dimissionauditrecord_set.all():
            if audit_obj.node == 'five' and audit_obj.node_name not in five_node_list:
                five_node_list.append(audit_obj.node_name)
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, "node_name": audit_obj.node_name, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.dimissionauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, "node_name": audit_obj.node_name, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"), 'file_type': atta_obj.file_type,
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        Rsk_obj = Company.objects.get(id=16).head_people
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list, 'five_node_list': five_node_list,
                   'is_edit': 'true' if obj.state == 'eight' and obj.user == request.user else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] and request.user == Rsk_obj else 'false',
                   "is_flag": 'true' if obj.group_grade in ['F1', 'F2', 'F3'] else 'false', "flow_dict": flow_dict,
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'back_management/ResignationApplicationDetail.html', context)

    def post(self, request):
        DimId = request.POST.get('DimId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Dim_obj = Dimission.objects.get(id=int(DimId))
        if types == 'delete':
            Dim_obj.dimissionauditrecord_set.all().delete()  # 清除审批列表
            Dim_obj.current_audit_users.clear()  # 清除当前审批
            Dim_obj.audit_users_already.clear()  # 清除已审批列表
            Dim_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人

            if state == "one":
                if not Dim_obj.dimissionauditrecord_set.filter(node="one"):
                    returnDict = {'message': '申请人为科室负责人，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Dim_obj.dimissionauditrecord_set.filter(node="one").all().delete()
                DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=audit_people_objs.first(), node='one', state='unaudit', audit_note='')
                Dim_obj.current_audit_users.clear()
                Dim_obj.audit_users_already.clear()
                Dim_obj.state = "one"
                Dim_obj.save()
                Dim_obj.current_audit_users.add(audit_people_objs.first())

                if Dim_obj.dimissionauditrecord_set.filter(node="two"):
                    two_step = Dim_obj.dimissionauditrecord_set.filter(node="two").last()
                    two_appave = two_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="two").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=two_appave, node='two', state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="three"):
                    three_step = Dim_obj.dimissionauditrecord_set.filter(node="three").last()
                    three_appave = three_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="three").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=three_appave, node='three', state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="four"):
                    four_step = Dim_obj.dimissionauditrecord_set.filter(node="four").last()
                    four_appave = four_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="four").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=four_appave, node='four', state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="five"):
                    five_step = Dim_obj.dimissionauditrecord_set.filter(node="five").last()
                    five_appave = five_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="five").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=five_appave, node='five', state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="six"):
                    six_step = Dim_obj.dimissionauditrecord_set.filter(node="six").last()
                    six_appave = six_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="six").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=six_appave, node='six', state='unaudit', audit_note='')

            elif state == "two":
                if not Dim_obj.dimissionauditrecord_set.filter(node="two"):
                    returnDict = {'message': '申请人无需报备，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

                Dim_obj.dimissionauditrecord_set.filter(node="two").all().delete()
                DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=audit_people_objs.first(), node='two', state='unaudit', audit_note='')
                Dim_obj.current_audit_users.clear()
                Dim_obj.audit_users_already.clear()
                Dim_obj.state = "two"
                Dim_obj.save()
                Dim_obj.current_audit_users.add(audit_people_objs.first())

                if Dim_obj.dimissionauditrecord_set.filter(node="three"):
                    three_step = Dim_obj.dimissionauditrecord_set.filter(node="three").last()
                    three_appave = three_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="three").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=three_appave, node='three', state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="four"):
                    four_step = Dim_obj.dimissionauditrecord_set.filter(node="four").last()
                    four_appave = four_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="four").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=four_appave, node='four', state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="five"):
                    five_step = Dim_obj.dimissionauditrecord_set.filter(node="five").last()
                    five_appave = five_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="five").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=five_appave, node='five', state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="six"):
                    six_step = Dim_obj.dimissionauditrecord_set.filter(node="six").last()
                    six_appave = six_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="six").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=six_appave, node='six', state='unaudit', audit_note='')

            elif state == "three":
                if not Dim_obj.dimissionauditrecord_set.filter(node="three"):
                    returnDict = {'message': '无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

                Dim_obj.dimissionauditrecord_set.filter(node="three").all().delete()
                DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=audit_people_objs.first(), node='three', state='unaudit', audit_note='')
                Dim_obj.current_audit_users.clear()
                Dim_obj.audit_users_already.clear()
                Dim_obj.state = "three"
                Dim_obj.save()
                Dim_obj.current_audit_users.add(audit_people_objs.first())

                if Dim_obj.dimissionauditrecord_set.filter(node="four"):
                    four_step = Dim_obj.dimissionauditrecord_set.filter(node="four").last()
                    four_appave = four_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="four").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=four_appave, node='four',
                                                        state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="five"):
                    five_step = Dim_obj.dimissionauditrecord_set.filter(node="five").last()
                    five_appave = five_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="five").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=five_appave, node='five',
                                                        state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="six"):
                    six_step = Dim_obj.dimissionauditrecord_set.filter(node="six").last()
                    six_appave = six_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="six").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=six_appave, node='six',
                                                        state='unaudit', audit_note='')

            elif state == "four":
                if not Dim_obj.dimissionauditrecord_set.filter(node="four"):
                    returnDict = {'message': '无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

                Dim_obj.dimissionauditrecord_set.filter(node="four").all().delete()
                DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=audit_people_objs.first(), node='four', state='unaudit', audit_note='')
                Dim_obj.current_audit_users.clear()
                Dim_obj.audit_users_already.clear()
                Dim_obj.state = "four"
                Dim_obj.save()
                Dim_obj.current_audit_users.add(audit_people_objs.first())

                if Dim_obj.dimissionauditrecord_set.filter(node="five"):
                    five_step = Dim_obj.dimissionauditrecord_set.filter(node="five").last()
                    five_appave = five_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="five").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=five_appave, node='five', state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="six"):
                    six_step = Dim_obj.dimissionauditrecord_set.filter(node="six").last()
                    six_appave = six_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="six").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=six_appave, node='six', state='unaudit', audit_note='')

            elif state == "five":
                if not Dim_obj.dimissionauditrecord_set.filter(node="five"):
                    returnDict = {'message': '无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

                Dim_obj.dimissionauditrecord_set.filter(node="five").all().delete()
                DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=audit_people_objs.first(), node='five', state='unaudit', audit_note='')
                Dim_obj.current_audit_users.clear()
                Dim_obj.audit_users_already.clear()
                Dim_obj.state = "five"
                Dim_obj.save()
                Dim_obj.current_audit_users.add(audit_people_objs.first())

                if Dim_obj.dimissionauditrecord_set.filter(node="six"):
                    six_step = Dim_obj.dimissionauditrecord_set.filter(node="six").last()
                    six_appave = six_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="six").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=six_appave, node='six', state='unaudit', audit_note='')

            elif state == "six":
                if not Dim_obj.dimissionauditrecord_set.filter(node="six"):
                    returnDict = {'message': '无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

                Dim_obj.dimissionauditrecord_set.filter(node="six").all().delete()
                DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=audit_people_objs.first(), node='six', state='unaudit', audit_note='')
                Dim_obj.current_audit_users.clear()
                Dim_obj.audit_users_already.clear()
                Dim_obj.state = "six"
                Dim_obj.save()
                Dim_obj.current_audit_users.add(audit_people_objs.first())

            else:
                Dim_obj.current_audit_users.clear()
                Dim_obj.audit_users_already.clear()
                Dim_obj.state = "eight"
                Dim_obj.save()
                Dim_obj.current_audit_users.add(Dim_obj.user)
                if Dim_obj.dimissionauditrecord_set.filter(node="one"):
                    one_step = Dim_obj.dimissionauditrecord_set.filter(node="one").last()
                    one_appave = one_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="one").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=one_appave, node='one', state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="two"):
                    two_step = Dim_obj.dimissionauditrecord_set.filter(node="two").last()
                    two_appave = two_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="two").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=two_appave, node='two', state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="three"):
                    three_step = Dim_obj.dimissionauditrecord_set.filter(node="three").last()
                    three_appave = three_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="three").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=three_appave, node='three', state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="four"):
                    four_step = Dim_obj.dimissionauditrecord_set.filter(node="four").last()
                    four_appave = four_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="four").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=four_appave, node='four', state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="five"):
                    five_step = Dim_obj.dimissionauditrecord_set.filter(node="five").last()
                    five_appave = five_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="five").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=five_appave, node='five', state='unaudit', audit_note='')

                if Dim_obj.dimissionauditrecord_set.filter(node="six"):
                    six_step = Dim_obj.dimissionauditrecord_set.filter(node="six").last()
                    six_appave = six_step.audit_people
                    Dim_obj.dimissionauditrecord_set.filter(node="six").all().delete()
                    DimissionAuditRecord.objects.create(parent_id=Dim_obj, audit_people=six_appave, node='six', state='unaudit', audit_note='')

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class SubjectFundingList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/SubjectFundingList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = SubjectFunding.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data) | Q(pay_reason__contains=search_data), state__in=['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'stop']).order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'pay_reason': obj.pay_reason,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      'state': obj.get_str_state(),
                      'total_money': obj.total_money}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SubjectFundingDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = SubjectFunding.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.subjectfundingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.subjectfundingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                          os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true',
                   'flow_dict': flow_dict, "revise": revise, "pay_detail": json.loads(obj.pay_detail),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'back_management/SubjectFundingDetail.html', context)

    def post(self, request):
        SubjectId = request.POST.get('SubjectId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Subject_obj = SubjectFunding.objects.get(id=SubjectId)
        if types == 'delete':
            Subject_obj.subjectfundingrecord_set.all().delete()  # 清除审批列表
            Subject_obj.current_audit_users.clear()  # 清除当前审批
            Subject_obj.audit_users_already.clear()  # 清除已审批列表
            Subject_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人

            if state != 'eight' and not audit_people_objs:
                returnDict = {'message': '请选择审批人！', "code": 400}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            if state == "one" or state == 'eight':
                if not Subject_obj.subjectfundingrecord_set.filter(node="one") and state == "one":
                    returnDict = {'message': '申请人为科室负责人，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Subject_obj.subjectfundingrecord_set.all().delete()
                Subject_obj.current_audit_users.clear()
                Subject_obj.audit_users_already.clear()
                if state == 'eight':
                    one_step = Subject_obj.company.head_people
                    if Subject_obj.apply_user != one_step:
                        SubjectFundingRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=Subject_obj)
                        Subject_obj.state = 'eight'
                        Subject_obj.current_audit_users.add(Subject_obj.apply_user)
                else:
                    SubjectFundingRecord.objects.create(parent_id=Subject_obj, audit_people=audit_people_objs.first(), node='one', state='unaudit', audit_note='')
                    Subject_obj.state = 'one'
                    Subject_obj.current_audit_users.add(audit_people_objs.first())

                Subject_obj.save()
                two_setp = Company.objects.get(id=14).head_people
                SubjectFundingRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=Subject_obj)

                three_setp = Company.objects.get(id=14).leaders_id
                SubjectFundingRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=Subject_obj)

                four_setp = Company.objects.get(id=23).head_people
                SubjectFundingRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=Subject_obj)

                five_setp = Company.objects.get(id=23).leaders_id if float(Subject_obj.total_money.replace(",", "")) <= 10000 else Staffing.objects.get(station='院长').post_personnel.all().first() if 10000 < float(Subject_obj.total_money.replace(",", "")) <= 200000 else Staffing.objects.get(station='书记').post_personnel.all().first()
                SubjectFundingRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=Subject_obj)

                six_setp = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                SubjectFundingRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=Subject_obj)
                Subject_obj.save()

            elif state == "two":
                if Subject_obj.state in ["one"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Subject_obj.subjectfundingrecord_set.filter(node__in=["two", "three", "four", "five", "six"]).delete()
                SubjectFundingRecord.objects.create(parent_id=Subject_obj, audit_people=audit_people_objs.first(), node='two', state='unaudit', audit_note='')
                Subject_obj.current_audit_users.clear()
                Subject_obj.state = 'two'
                Subject_obj.save()
                Subject_obj.current_audit_users.add(audit_people_objs.first())

                three_setp = Company.objects.get(id=14).leaders_id
                SubjectFundingRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=Subject_obj)

                four_setp = Company.objects.get(id=23).head_people
                SubjectFundingRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=Subject_obj)

                five_setp = Company.objects.get(id=23).leaders_id if float(Subject_obj.total_money.replace(",", "")) <= 10000 else Staffing.objects.get(station='院长').post_personnel.all().first() if 10000 < float(Subject_obj.total_money.replace(",", "")) <= 200000 else Staffing.objects.get(station='书记').post_personnel.all().first()
                SubjectFundingRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=Subject_obj)

                six_setp = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                SubjectFundingRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=Subject_obj)
                Subject_obj.save()

            elif state == "three":
                if Subject_obj.state in ["one", "two"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Subject_obj.subjectfundingrecord_set.filter(node__in=["three", "four", "five", "six"]).delete()
                SubjectFundingRecord.objects.create(parent_id=Subject_obj, audit_people=audit_people_objs.first(), node='three', state='unaudit', audit_note='')
                Subject_obj.current_audit_users.clear()
                Subject_obj.state = 'three'
                Subject_obj.save()
                Subject_obj.current_audit_users.add(audit_people_objs.first())

                four_setp = Company.objects.get(id=23).head_people
                SubjectFundingRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=Subject_obj)

                five_setp = Company.objects.get(id=23).leaders_id if float(Subject_obj.total_money.replace(",", "")) <= 10000 else Staffing.objects.get(station='院长').post_personnel.all().first() if 10000 < float(Subject_obj.total_money.replace(",", "")) <= 200000 else Staffing.objects.get(station='书记').post_personnel.all().first()
                SubjectFundingRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=Subject_obj)

                six_setp = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                SubjectFundingRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=Subject_obj)
                Subject_obj.save()

            elif state == "four":
                if Subject_obj.state in ["one", "two", "three"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Subject_obj.subjectfundingrecord_set.filter(node__in=["four", "five", "six"]).delete()
                SubjectFundingRecord.objects.create(parent_id=Subject_obj, audit_people=audit_people_objs.first(), node='four', state='unaudit', audit_note='')
                Subject_obj.current_audit_users.clear()
                Subject_obj.state = 'four'
                Subject_obj.save()
                Subject_obj.current_audit_users.add(audit_people_objs.first())

                five_setp = Company.objects.get(id=23).leaders_id if float(Subject_obj.total_money.replace(",", "")) <= 10000 else Staffing.objects.get(station='院长').post_personnel.all().first() if 10000 < float(Subject_obj.total_money.replace(",", "")) <= 200000 else Staffing.objects.get(station='书记').post_personnel.all().first()
                SubjectFundingRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=Subject_obj)

                six_setp = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                SubjectFundingRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=Subject_obj)
                Subject_obj.save()

            elif state == "five":
                if Subject_obj.state in ["one", "two", "three", "four"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Subject_obj.subjectfundingrecord_set.filter(node__in=["five", "six"]).delete()
                SubjectFundingRecord.objects.create(parent_id=Subject_obj, audit_people=audit_people_objs.first(), node='five', state='unaudit', audit_note='')
                Subject_obj.current_audit_users.clear()
                Subject_obj.state = 'five'
                Subject_obj.save()
                Subject_obj.current_audit_users.add(audit_people_objs.first())

                six_setp = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                SubjectFundingRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=Subject_obj)
                Subject_obj.save()

            else:
                if Subject_obj.state in ["one", "two", "three", "four", "five"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Subject_obj.subjectfundingrecord_set.filter(node__in=["six"]).delete()
                SubjectFundingRecord.objects.create(parent_id=Subject_obj, audit_people=audit_people_objs.first(), node='six', state='unaudit', audit_note='')
                Subject_obj.current_audit_users.clear()
                Subject_obj.state = 'six'
                Subject_obj.save()
                Subject_obj.current_audit_users.add(audit_people_objs.first())

                Subject_obj.save()

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class TradeUnionOutlaysList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/TradeUnionOutlaysList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = LaborUnionExpenses.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), state__in=['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'stop']).order_by('-create_time')
        print(objs.count())
        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'payee': obj.payee, 'total_money': obj.total_money,
             'pay_reason': obj.pay_reason,
             'state': obj.get_str_state(),
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()])}
            for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class TradeUnionOutlaysDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = LaborUnionExpenses.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.laborunionexpensesrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.laborunionexpensesrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                          os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {"obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six", "nine"] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', "nine"] and request.user == obj.apply_user else 'false',
                   'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'back_management/TradeUnionOutlaysDetail.html', context)

    def post(self, request):
        TradeId = request.POST.get('TradeId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Trade_obj = LaborUnionExpenses.objects.get(id=TradeId)
        if types == 'delete':
            Trade_obj.laborunionexpensesrecord_set.all().delete()  # 清除审批列表
            Trade_obj.current_audit_users.clear()  # 清除当前审批
            Trade_obj.audit_users_already.clear()  # 清除已审批列表
            Trade_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人

            if state != 'eight' and not audit_people_objs:
                returnDict = {'message': '请选择审批人！', "code": 400}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            if state == "one" or state == 'eight':
                if not Trade_obj.laborunionexpensesrecord_set.filter(node="one") and state == "one":
                    returnDict = {'message': '申请人为科室负责人，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Trade_obj.laborunionexpensesrecord_set.all().delete()
                Trade_obj.current_audit_users.clear()
                if state == 'eight':
                    Trade_obj.state = 'eight'
                    Trade_obj.current_audit_users.add(Trade_obj.apply_user)
                    one_step = Trade_obj.company.head_people
                    if Trade_obj.apply_user != one_step:
                        LaborUnionExpensesRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=Trade_obj)
                else:
                    LaborUnionExpensesRecord.objects.create(parent_id=Trade_obj, audit_people=audit_people_objs.first(), node='one', state='unaudit', audit_note='')
                    Trade_obj.state = 'one'
                    Trade_obj.current_audit_users.add(audit_people_objs.first())
                Trade_obj.save()

                htkj_obj = Staffing.objects.get(station='工会经费审核会计').post_personnel.all()
                for htkj in htkj_obj:
                    LaborUnionExpensesRecord.objects.create(node='two', audit_note='', audit_people=htkj, parent_id=Trade_obj, state='unaudit')

                three_setp = Company.objects.get(id=22).head_people
                LaborUnionExpensesRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=Trade_obj, state='unaudit')

                four_step = Company.objects.get(id=23).head_people
                LaborUnionExpensesRecord.objects.create(node='four', audit_note='', audit_people=four_step, parent_id=Trade_obj, state='unaudit')

                LaborUnionExpensesRecord.objects.create(node='five', audit_note='', audit_people=Trade_obj.company.leaders_id, parent_id=Trade_obj, state='unaudit')

                if float(Trade_obj.total_money.replace(",", "")) < 10000:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='工会主席').post_personnel.all().first(), parent_id=Trade_obj)
                elif 1000 <= float(Trade_obj.total_money.replace(",", "")) < 200000:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=Trade_obj)
                else:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), parent_id=Trade_obj)

                LaborUnionExpensesRecord.objects.create(node='nine', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='财务出纳').post_personnel.all().first(), parent_id=Trade_obj)
                Trade_obj.save()

            elif state == "two":
                if Trade_obj.state in ["one"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Trade_obj.laborunionexpensesrecord_set.filter(node__in=["two", "three", "four", "five", "six", "nine"]).delete()
                Trade_obj.current_audit_users.clear()
                htkj_obj = Staffing.objects.get(station='工会经费审核会计').post_personnel.all()
                for htkj in htkj_obj:
                    LaborUnionExpensesRecord.objects.create(node='two', audit_note='', audit_people=htkj, parent_id=Trade_obj, state='unaudit')
                    Trade_obj.current_audit_users.add(htkj)

                three_setp = Company.objects.get(id=22).head_people
                LaborUnionExpensesRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=Trade_obj, state='unaudit')

                four_step = Company.objects.get(id=23).head_people
                LaborUnionExpensesRecord.objects.create(node='four', audit_note='', audit_people=four_step, parent_id=Trade_obj, state='unaudit')

                LaborUnionExpensesRecord.objects.create(node='five', audit_note='', audit_people=Trade_obj.company.leaders_id, parent_id=Trade_obj, state='unaudit')

                if float(Trade_obj.total_money.replace(",", "")) < 10000:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='工会主席').post_personnel.all().first(), parent_id=Trade_obj)
                elif 1000 <= float(Trade_obj.total_money.replace(",", "")) < 200000:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=Trade_obj)
                else:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), parent_id=Trade_obj)

                LaborUnionExpensesRecord.objects.create(node='nine', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='财务出纳').post_personnel.all().first(), parent_id=Trade_obj)
                Trade_obj.state = "two"
                Trade_obj.save()

            elif state == "three":
                if Trade_obj.state in ["one", "two"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Trade_obj.laborunionexpensesrecord_set.filter(node__in=["three", "four", "five", "six", "nine"]).delete()
                Trade_obj.current_audit_users.clear()

                LaborUnionExpensesRecord.objects.create(node='three', audit_note='', audit_people=audit_people_objs.first(), parent_id=Trade_obj, state='unaudit')
                Trade_obj.current_audit_users.add(audit_people_objs.first())

                four_step = Company.objects.get(id=23).head_people
                LaborUnionExpensesRecord.objects.create(node='four', audit_note='', audit_people=four_step, parent_id=Trade_obj, state='unaudit')

                LaborUnionExpensesRecord.objects.create(node='five', audit_note='', audit_people=Trade_obj.company.leaders_id, parent_id=Trade_obj, state='unaudit')

                if float(Trade_obj.total_money.replace(",", "")) < 10000:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='工会主席').post_personnel.all().first(), parent_id=Trade_obj)
                elif 1000 <= float(Trade_obj.total_money.replace(",", "")) < 200000:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=Trade_obj)
                else:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), parent_id=Trade_obj)

                LaborUnionExpensesRecord.objects.create(node='nine', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='财务出纳').post_personnel.all().first(), parent_id=Trade_obj)
                Trade_obj.state = "three"
                Trade_obj.save()

            elif state == "four":
                if Trade_obj.state in ["one", "two", "three"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Trade_obj.laborunionexpensesrecord_set.filter(node__in=["four", "five", "six", "nine"]).delete()
                Trade_obj.current_audit_users.clear()

                LaborUnionExpensesRecord.objects.create(node='four', audit_note='', audit_people=audit_people_objs.first(), parent_id=Trade_obj, state='unaudit')
                Trade_obj.current_audit_users.add(audit_people_objs.first())

                LaborUnionExpensesRecord.objects.create(node='five', audit_note='', audit_people=Trade_obj.company.leaders_id, parent_id=Trade_obj, state='unaudit')

                if float(Trade_obj.total_money.replace(",", "")) < 10000:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='工会主席').post_personnel.all().first(), parent_id=Trade_obj)
                elif 1000 <= float(Trade_obj.total_money.replace(",", "")) < 200000:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=Trade_obj)
                else:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), parent_id=Trade_obj)

                LaborUnionExpensesRecord.objects.create(node='nine', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='财务出纳').post_personnel.all().first(), parent_id=Trade_obj)
                Trade_obj.state = "four"
                Trade_obj.save()

            elif state == "five":
                if Trade_obj.state in ["four", "one", "two", "three"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Trade_obj.laborunionexpensesrecord_set.filter(node__in=["five", "six", "nine"]).delete()
                Trade_obj.current_audit_users.clear()

                LaborUnionExpensesRecord.objects.create(node='five', audit_note='', audit_people=audit_people_objs.first(), parent_id=Trade_obj, state='unaudit')
                Trade_obj.current_audit_users.add(audit_people_objs.first())

                if float(Trade_obj.total_money.replace(",", "")) < 10000:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='工会主席').post_personnel.all().first(), parent_id=Trade_obj)
                elif 1000 <= float(Trade_obj.total_money.replace(",", "")) < 200000:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=Trade_obj)
                else:
                    LaborUnionExpensesRecord.objects.create(node='six', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), parent_id=Trade_obj)

                LaborUnionExpensesRecord.objects.create(node='nine', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='财务出纳').post_personnel.all().first(), parent_id=Trade_obj)
                Trade_obj.state = "five"
                Trade_obj.save()

            elif state == "six":
                if Trade_obj.state in ["five", "four", "one", "two", "three"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Trade_obj.laborunionexpensesrecord_set.filter(node__in=["six", "nine"]).delete()
                Trade_obj.current_audit_users.clear()

                LaborUnionExpensesRecord.objects.create(node='six', audit_note='', audit_people=audit_people_objs.first(), parent_id=Trade_obj, state='unaudit')
                Trade_obj.current_audit_users.add(audit_people_objs.first())

                LaborUnionExpensesRecord.objects.create(node='nine', state='unaudit', audit_note='', audit_people=Staffing.objects.get(station='财务出纳').post_personnel.all().first(), parent_id=Trade_obj)
                Trade_obj.state = "six"
                Trade_obj.save()

            else:
                if Trade_obj.state in ["six", "five", "four", "one", "two", "three"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Trade_obj.laborunionexpensesrecord_set.filter(node__in=["six", "nine"]).delete()
                Trade_obj.current_audit_users.clear()

                LaborUnionExpensesRecord.objects.create(node='nine', audit_note='', audit_people=audit_people_objs.first(), parent_id=Trade_obj, state='unaudit')
                Trade_obj.current_audit_users.add(audit_people_objs.first())

                Trade_obj.state = "nine"
                Trade_obj.save()

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class QuickAuthorizationList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/QuickAuthorizationList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = QuickAuthorization.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data), state__in=['one', 'two', 'three', 'four', 'seven', 'eight', 'stop']).order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'seal_name': ', '.join([u.seal_name for u in obj.seal_name.all()]),
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      'state': obj.get_state_str(),
                      "title": "用印快捷授权"} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class QuickAuthorizationDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        seal_obj = seal.objects.all()
        obj = QuickAuthorization.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.quickauthorizationrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.quickauthorizationrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        if obj.authorization_type == '法人授权':
            if obj.state in ["one", "two"]:
                ApprovalType = "approval"
            else:
                ApprovalType = "receive"
        else:
            if obj.state in ["one", "three"]:
                ApprovalType = "approval"
            else:
                ApprovalType = "receive"

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "seal_obj": seal_obj,
                   'seal_list': [i.id for i in obj.seal_name.all()],
                   'seal_name': ', '.join([i.seal_name for i in obj.seal_name.all()]),
                   'is_edit': 'true',
                   'reason': json.loads(obj.reason), "ApprovalType": ApprovalType,
                   'flow_dict': flow_dict, "revise": revise}
        return render(request, 'back_management/QuickAuthorizationDetail.html', context)

    def post(self, request):
        QuickId = request.POST.get('QuickId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Quick_obj = QuickAuthorization.objects.get(id=QuickId)
        if types == 'delete':
            Quick_obj.quickauthorizationrecord_set.all().delete()  # 清除审批列表
            Quick_obj.current_audit_users.clear()  # 清除当前审批
            Quick_obj.audit_users_already.clear()  # 清除已审批列表
            Quick_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人

            if state == "one" or state == 'eight':
                Quick_obj.quickauthorizationrecord_set.all().delete()
                Quick_obj.current_audit_users.clear()
                Quick_obj.audit_users_already.clear()
                if state == 'eight':
                    Quick_obj.state = 'eight'
                    Quick_obj.current_audit_users.add(Quick_obj.apply_user)
                    QuickAuthorizationRecord.objects.create(node='one', audit_note='', audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), parent_id=Quick_obj)
                else:
                    QuickAuthorizationRecord.objects.create(parent_id=Quick_obj, audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), node='one', state='unaudit', audit_note='')
                    Quick_obj.state = 'one'
                    Quick_obj.current_audit_users.add(Staffing.objects.get(station="院长").post_personnel.all().first())
                QuickAuthorizationRecord.objects.create(node='two', audit_note='', audit_people=Quick_obj.apply_user, parent_id=Quick_obj, state='unaudit')
                Quick_obj.save()

            else:
                if Quick_obj.state == "one":
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Quick_obj.quickauthorizationrecord_set.filter(node='two').delete()
                Quick_obj.current_audit_users.clear()

                QuickAuthorizationRecord.objects.create(node='two', audit_note='', audit_people=Quick_obj.apply_user, parent_id=Quick_obj, state='unaudit')
                Quick_obj.current_audit_users.add(Quick_obj.apply_user)

                Quick_obj.state = "two"
                Quick_obj.save()

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class NewspaperCustomizationList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/NewspaperCustomizationList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = BookSubscription.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data), state__in=['one', 'two', 'three', 'four', 'seven', 'eight', 'stop']).order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      'state': obj.get_state_str(), "title": "图书/报刊/杂志征订"}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class NewspaperCustomizationDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = BookSubscription.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.booksubscriptionrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.booksubscriptionrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic,
                   'reason': json.loads(obj.reason), 'book_buy': json.loads(obj.book_buy),
                   'is_edit': 'true',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   'flow_dict': flow_dict, "revise": revise}
        return render(request, "back_management/NewspaperCustomizationDetail.html", context)

    def post(self, request):
        NewspaperId = request.POST.get('NewspaperId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Newspaper_obj = BookSubscription.objects.get(id=NewspaperId)
        if types == 'delete':
            Newspaper_obj.booksubscriptionrecord_set.all().delete()  # 清除审批列表
            Newspaper_obj.current_audit_users.clear()  # 清除当前审批
            Newspaper_obj.audit_users_already.clear()  # 清除已审批列表
            Newspaper_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人

            if state == "one" or state == 'eight':
                if not Newspaper_obj.booksubscriptionrecord_set.filter(node="one") and state == "one":
                    returnDict = {'message': '申请人为科室负责人，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Newspaper_obj.booksubscriptionrecord_set.all().delete()
                Newspaper_obj.current_audit_users.clear()
                Newspaper_obj.audit_users_already.clear()
                if state == 'eight':
                    Newspaper_obj.state = 'eight'
                    Newspaper_obj.current_audit_users.add(Newspaper_obj.apply_user)
                    director_people = Newspaper_obj.company.head_people
                    if Newspaper_obj.apply_user != director_people:
                        BookSubscriptionRecord.objects.create(node="one", state='unaudit', audit_people=director_people, parent_id=Newspaper_obj)
                else:
                    BookSubscriptionRecord.objects.create(parent_id=Newspaper_obj, audit_people=audit_people_objs.first(), node='one', state='unaudit', audit_note='')
                    Newspaper_obj.state = 'one'
                    Newspaper_obj.current_audit_users.add(audit_people_objs.first())

                two_step = Staffing.objects.get(station='图书管理员').post_personnel.all()
                for sa in two_step:
                    BookSubscriptionRecord.objects.create(node="two", state='unaudit', audit_people=sa, parent_id=Newspaper_obj)
                Batjk = Company.objects.get(id=24)
                three_step = Batjk.head_people
                BookSubscriptionRecord.objects.create(node="three", state='unaudit', audit_people=three_step, parent_id=Newspaper_obj)
                BookSubscriptionRecord.objects.create(node="four", state='unaudit', audit_people=Batjk.leaders_id, parent_id=Newspaper_obj)

            elif state == "two":
                Newspaper_obj.state = 'two'
                Newspaper_obj.booksubscriptionrecord_set.filter(node__in=["two", "three", "four"]).delete()
                Newspaper_obj.current_audit_users.clear()
                two_step = Staffing.objects.get(station='图书管理员').post_personnel.all()
                for sa in two_step:
                    BookSubscriptionRecord.objects.create(node="two", state='unaudit', audit_people=sa, parent_id=Newspaper_obj)
                    Newspaper_obj.current_audit_users.add(sa)
                Batjk = Company.objects.get(id=24)
                three_step = Batjk.head_people
                BookSubscriptionRecord.objects.create(node="three", state='unaudit', audit_people=three_step, parent_id=Newspaper_obj)
                BookSubscriptionRecord.objects.create(node="four", state='unaudit', audit_people=Batjk.leaders_id, parent_id=Newspaper_obj)

            elif state == "three":
                Newspaper_obj.state = 'three'
                Newspaper_obj.booksubscriptionrecord_set.filter(node__in=["three", "four"]).delete()
                Newspaper_obj.current_audit_users.clear()
                Batjk = Company.objects.get(id=24)
                Newspaper_obj.current_audit_users.add(audit_people_objs.first())
                BookSubscriptionRecord.objects.create(node="three", state='unaudit', audit_people=audit_people_objs.first(), parent_id=Newspaper_obj)
                BookSubscriptionRecord.objects.create(node="four", state='unaudit', audit_people=Batjk.leaders_id, parent_id=Newspaper_obj)

            else:
                Newspaper_obj.state = 'four'
                Newspaper_obj.booksubscriptionrecord_set.filter(node="four").delete()
                Newspaper_obj.current_audit_users.clear()
                Newspaper_obj.current_audit_users.add(audit_people_objs.first())
                BookSubscriptionRecord.objects.create(node="four", state='unaudit', audit_people=audit_people_objs.first(), parent_id=Newspaper_obj)

            Newspaper_obj.save()
            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class PartyGovernmentList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/PartyGovernmentList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = PartyBuilding.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data), state__in=['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'stop']).order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      'state': obj.get_state_str(), "title": "党建经费申请"}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class PartyGovernmentDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = PartyBuilding.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.partybuildingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.partybuildingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {"obj": obj, 'audit_dic': audit_dic, "file_list": file_list, "pay_detail": json.loads(obj.pay_detail), 'is_edit': 'true',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six"] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user == obj.apply_user else 'false',
                   'flow_dict': flow_dict, "revise": revise, "branch_review_obj": Staffing.objects.get(station='支部书记').post_personnel.all(),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'back_management/PartyGovernmentDetail.html', context)

    def post(self, request):
        PartyId = request.POST.get('PartyId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Party_obj = PartyBuilding.objects.get(id=PartyId)
        if types == 'delete':
            Party_obj.partybuildingrecord_set.all().delete()  # 清除审批列表
            Party_obj.current_audit_users.clear()  # 清除当前审批
            Party_obj.audit_users_already.clear()  # 清除已审批列表
            Party_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人

            if state == "one" or state == 'eight':
                if not Party_obj.partybuildingrecord_set.filter(node="one") and state == "one":
                    returnDict = {'message': '无该节点，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Party_obj.partybuildingrecord_set.all().delete()
                Party_obj.current_audit_users.clear()
                Party_obj.audit_users_already.clear()
                if state == 'eight':
                    Party_obj.state = 'eight'
                    Party_obj.current_audit_users.add(Party_obj.apply_user)

                    if Party_obj.branch_review:
                        PartyBuildingRecord.objects.create(node="one", state='unaudit', audit_people=Party_obj.branch_review, parent_id=Party_obj)
                else:
                    if not audit_people_objs:
                        returnDict = {'message': '请选择审批人！', "code": 400}
                        return HttpResponse(json.dumps(returnDict), content_type="application/json")
                    PartyBuildingRecord.objects.create(parent_id=Party_obj, audit_people=audit_people_objs.first(), node='one', state='unaudit', audit_note='')
                    Party_obj.state = 'one'
                    Party_obj.current_audit_users.add(audit_people_objs.first())

                two_prave = Company.objects.get(id=3).head_people
                PartyBuildingRecord.objects.create(node="two", state='unaudit', audit_people=two_prave, parent_id=Party_obj)
                PartyBuildingRecord.objects.create(node="three", state='unaudit', audit_people=Company.objects.get(id=3).leaders_id, parent_id=Party_obj)
                four_prave = Company.objects.get(id=23).head_people
                PartyBuildingRecord.objects.create(node="four", state='unaudit', audit_people=four_prave, parent_id=Party_obj)
                five_prave = Company.objects.get(id=23).leaders_id if float(Party_obj.total_amount.replace(",", '')) <= 10000 else \
                    Staffing.objects.get(station="院长").post_personnel.all().first() if 10000 < float(Party_obj.total_amount.replace(",", '')) < 200000 else \
                        Staffing.objects.get(station="书记").post_personnel.all().first()
                PartyBuildingRecord.objects.create(node="five", state='unaudit', audit_people=five_prave, parent_id=Party_obj, audit_note='')

                PartyBuildingRecord.objects.create(node="six", state='unaudit', audit_people=Staffing.objects.get(station="财务支付").post_personnel.all().first(), parent_id=Party_obj, audit_note='')

            elif state == "two":
                if not audit_people_objs:
                    returnDict = {'message': '请选择审批人！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Party_obj.state = 'two'
                Party_obj.partybuildingrecord_set.filter(node__in=["two", "three", "four", "five", "six"]).delete()
                Party_obj.current_audit_users.clear()

                PartyBuildingRecord.objects.create(node="two", state='unaudit', audit_people=audit_people_objs.first(), parent_id=Party_obj)
                Party_obj.current_audit_users.add(audit_people_objs.first())
                PartyBuildingRecord.objects.create(node="three", state='unaudit', audit_people=Company.objects.get(id=3).leaders_id, parent_id=Party_obj)
                four_prave = Company.objects.get(id=23).head_people
                PartyBuildingRecord.objects.create(node="four", state='unaudit', audit_people=four_prave, parent_id=Party_obj)
                five_prave = Company.objects.get(id=23).leaders_id if float(Party_obj.total_amount.replace(",", '')) <= 10000 else \
                    Staffing.objects.get(station="院长").post_personnel.all().first() if 10000 < float(Party_obj.total_amount.replace(",", '')) < 200000 else \
                        Staffing.objects.get(station="书记").post_personnel.all().first()
                PartyBuildingRecord.objects.create(node="five", state='unaudit', audit_people=five_prave, parent_id=Party_obj, audit_note='')

                PartyBuildingRecord.objects.create(node="six", state='unaudit', audit_people=Staffing.objects.get(station="财务支付").post_personnel.all().first(), parent_id=Party_obj, audit_note='')

            elif state == "three":
                if not audit_people_objs:
                    returnDict = {'message': '请选择审批人！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Party_obj.state = 'three'
                Party_obj.partybuildingrecord_set.filter(node__in=["three", "four", "five", "six"]).delete()
                Party_obj.current_audit_users.clear()
                Party_obj.current_audit_users.add(audit_people_objs.first())
                PartyBuildingRecord.objects.create(node="three", state='unaudit', audit_people=audit_people_objs.first(), parent_id=Party_obj)
                four_prave = Company.objects.get(id=23).head_people
                PartyBuildingRecord.objects.create(node="four", state='unaudit', audit_people=four_prave, parent_id=Party_obj)
                five_prave = Company.objects.get(id=23).leaders_id if float(Party_obj.total_amount.replace(",", '')) <= 10000 else \
                    Staffing.objects.get(station="院长").post_personnel.all().first() if 10000 < float(Party_obj.total_amount.replace(",", '')) < 200000 else \
                        Staffing.objects.get(station="书记").post_personnel.all().first()
                PartyBuildingRecord.objects.create(node="five", state='unaudit', audit_people=five_prave, parent_id=Party_obj, audit_note='')

                PartyBuildingRecord.objects.create(node="six", state='unaudit', audit_people=Staffing.objects.get(station="财务支付").post_personnel.all().first(), parent_id=Party_obj, audit_note='')

            elif state == "four":
                if not audit_people_objs:
                    returnDict = {'message': '请选择审批人！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Party_obj.state = 'four'
                Party_obj.partybuildingrecord_set.filter(node__in=["four", "five", "six"]).delete()
                Party_obj.current_audit_users.clear()
                Party_obj.current_audit_users.add(audit_people_objs.first())
                PartyBuildingRecord.objects.create(node="four", state='unaudit', audit_people=audit_people_objs.first(), parent_id=Party_obj)
                five_prave = Company.objects.get(id=23).leaders_id if float(Party_obj.total_amount.replace(",", '')) <= 10000 else \
                    Staffing.objects.get(station="院长").post_personnel.all().first() if 10000 < float(Party_obj.total_amount.replace(",", '')) < 200000 else \
                        Staffing.objects.get(station="书记").post_personnel.all().first()
                PartyBuildingRecord.objects.create(node="five", state='unaudit', audit_people=five_prave, parent_id=Party_obj, audit_note='')

                PartyBuildingRecord.objects.create(node="six", state='unaudit', audit_people=Staffing.objects.get(station="财务支付").post_personnel.all().first(), parent_id=Party_obj, audit_note='')

            elif state == "five":
                if not audit_people_objs:
                    returnDict = {'message': '请选择审批人！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Party_obj.state = 'five'
                Party_obj.partybuildingrecord_set.filter(node__in=["five", "six"]).delete()
                Party_obj.current_audit_users.clear()
                Party_obj.current_audit_users.add(audit_people_objs.first())
                PartyBuildingRecord.objects.create(node="five", state='unaudit', audit_people=audit_people_objs.first(), parent_id=Party_obj)
                PartyBuildingRecord.objects.create(node="six", state='unaudit', audit_people=Staffing.objects.get(station="财务支付").post_personnel.all().first(), parent_id=Party_obj, audit_note='')


            else:
                if not audit_people_objs:
                    returnDict = {'message': '请选择审批人！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Party_obj.state = 'six'
                Party_obj.partybuildingrecord_set.filter(node="six").delete()
                Party_obj.current_audit_users.clear()
                Party_obj.current_audit_users.add(audit_people_objs.first())
                PartyBuildingRecord.objects.create(node="six", state='unaudit', audit_people=audit_people_objs.first(), parent_id=Party_obj)

            Party_obj.save()
            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class AuthorizationUseSeal(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        returndata = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in returndata:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)

        Qu_obj = QuickAuthorization.objects.filter(state='seven', can_related='1')
        return render(request, "back_management/AuthorizationUseSeal.html", {"company_list": company_list, "Qu_obj": Qu_obj})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = QuickAuthorizationSeal.objects.filter().order_by('-create_time')

        str_count, str_list = 1, []
        data_list = []
        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            data_list.append({'id': obj.id, "title": "法人授权" if obj.authorization_type == '1' else "分管授权", 'dep': obj.company.name})

        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class AddAuthorization(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        seal_obj = seal.objects.all()
        leader_obj = User.objects.filter(group=2)
        return render(request, "back_management/AddAuthorization.html", {"seal_obj": seal_obj, 'company_list': [{'id': com.id, 'name': com.name} for com in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")], "leader_obj": leader_obj})

class AddAuthorizationDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        seal_obj = seal.objects.all()

        flow_id = request.GET.get('id', '')
        obj = QuickAuthorizationSeal.objects.get(id=int(flow_id))
        detail_json = json.loads(obj.detail_json)
        leader_obj = User.objects.filter(group=2)
        return render(request, "back_management/AddAuthorizationDetail.html", {"seal_obj": seal_obj, 'company_list': [{'id': com.id, 'name': com.name} for com in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")],
                                "obj": obj, "detail_json": detail_json, "leader_obj": leader_obj})

    def post(self, request):
        flow_id = request.POST.get("id", '')  # 流程ID
        print(flow_id)
        obj = QuickAuthorizationSeal.objects.get(id=int(flow_id))
        if obj.can_related == '1':
            obj.delete()
            returnDict = {'message': '删除成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        returnDict = {'message': '该流程已快捷授权，无法删除！！！', "code": 400}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ResearchFundingList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/ResearchFundingList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = ResearchFunding.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(company__name__contains=search_data) | Q(pay_reason__contains=search_data), state__in=['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'stop']).order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'pay_reason': obj.pay_reason,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      'state': obj.get_str_state(),
                      'total_money': obj.total_money}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ResearchFundingDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ResearchFunding.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.researchfundingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.researchfundingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                          os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true',
                   'flow_dict': flow_dict, "revise": revise, "pay_detail": json.loads(obj.pay_detail),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'back_management/ResearchFundingDetail.html', context)

    def post(self, request):
        SubjectId = request.POST.get('SubjectId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Subject_obj = ResearchFunding.objects.get(id=SubjectId)
        if types == 'delete':
            Subject_obj.researchfundingrecord_set.all().delete()  # 清除审批列表
            Subject_obj.current_audit_users.clear()  # 清除当前审批
            Subject_obj.audit_users_already.clear()  # 清除已审批列表
            Subject_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人

            if state != 'eight' and not audit_people_objs:
                returnDict = {'message': '请选择审批人！', "code": 400}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            if state == "one" or state == 'eight':
                if not Subject_obj.researchfundingrecord_set.filter(node="one") and state == "one":
                    returnDict = {'message': '申请人为科室负责人，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Subject_obj.researchfundingrecord_set.all().delete()
                Subject_obj.current_audit_users.clear()
                Subject_obj.audit_users_already.clear()
                if state == 'eight':
                    Subject_obj.state = 'eight'
                    Subject_obj.current_audit_users.add(Subject_obj.apply_user)
                    one_step = Subject_obj.company.head_people
                    if Subject_obj.apply_user != one_step:
                        ResearchFundingRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=Subject_obj)
                else:
                    ResearchFundingRecord.objects.create(parent_id=Subject_obj, audit_people=audit_people_objs.first(), node='one', state='unaudit', audit_note='')
                    Subject_obj.state = 'one'
                    Subject_obj.current_audit_users.add(audit_people_objs.first())

                Subject_obj.save()
                two_setp = Company.objects.get(id=14).head_people
                ResearchFundingRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=Subject_obj)

                three_setp = Company.objects.get(id=14).leaders_id
                ResearchFundingRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=Subject_obj)

                four_setp = Company.objects.get(id=23).head_people
                ResearchFundingRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=Subject_obj)

                five_setp = Company.objects.get(id=23).leaders_id if float(
                    Subject_obj.total_money.replace(",", "")) <= 10000 else Staffing.objects.get(
                    station='院长').post_personnel.all().first() if 10000 < float(
                    Subject_obj.total_money.replace(",", "")) <= 200000 else Staffing.objects.get(
                    station='书记').post_personnel.all().first()
                ResearchFundingRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=Subject_obj)

                six_setp = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                ResearchFundingRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=Subject_obj)
                Subject_obj.save()

            elif state == "two":
                if Subject_obj.state in ["one"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Subject_obj.researchfundingrecord_set.filter(node__in=["two", "three", "four", "five", "six"]).delete()
                ResearchFundingRecord.objects.create(parent_id=Subject_obj, audit_people=audit_people_objs.first(), node='two', state='unaudit', audit_note='')
                Subject_obj.current_audit_users.clear()
                Subject_obj.state = 'two'
                Subject_obj.save()
                Subject_obj.current_audit_users.add(audit_people_objs.first())

                three_setp = Company.objects.get(id=14).leaders_id
                ResearchFundingRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=Subject_obj)

                four_setp = Company.objects.get(id=23).head_people
                ResearchFundingRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=Subject_obj)

                five_setp = Company.objects.get(id=23).leaders_id if float(Subject_obj.total_money.replace(",", "")) <= 10000 else Staffing.objects.get(station='院长').post_personnel.all().first() if 10000 < float(Subject_obj.total_money.replace(",", "")) <= 200000 else Staffing.objects.get(station='书记').post_personnel.all().first()
                ResearchFundingRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=Subject_obj)

                six_setp = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                ResearchFundingRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=Subject_obj)
                Subject_obj.save()

            elif state == "three":
                if Subject_obj.state in ["one", "two"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Subject_obj.researchfundingrecord_set.filter(node__in=["three", "four", "five", "six"]).delete()
                ResearchFundingRecord.objects.create(parent_id=Subject_obj, audit_people=audit_people_objs.first(), node='three', state='unaudit', audit_note='')
                Subject_obj.current_audit_users.clear()
                Subject_obj.state = 'three'
                Subject_obj.save()
                Subject_obj.current_audit_users.add(audit_people_objs.first())

                four_setp = Company.objects.get(id=23).head_people
                ResearchFundingRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=Subject_obj)

                five_setp = Company.objects.get(id=23).leaders_id if float(Subject_obj.total_money.replace(",", "")) <= 10000 else Staffing.objects.get(station='院长').post_personnel.all().first() if 10000 < float(Subject_obj.total_money.replace(",", "")) <= 200000 else Staffing.objects.get(station='书记').post_personnel.all().first()
                ResearchFundingRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=Subject_obj)

                six_setp = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                ResearchFundingRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=Subject_obj)
                Subject_obj.save()

            elif state == "four":
                if Subject_obj.state in ["one", "two", "three"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Subject_obj.researchfundingrecord_set.filter(node__in=["four", "five", "six"]).delete()
                ResearchFundingRecord.objects.create(parent_id=Subject_obj, audit_people=audit_people_objs.first(), node='four', state='unaudit', audit_note='')
                Subject_obj.current_audit_users.clear()
                Subject_obj.state = 'four'
                Subject_obj.save()
                Subject_obj.current_audit_users.add(audit_people_objs.first())

                five_setp = Company.objects.get(id=23).leaders_id if float(Subject_obj.total_money.replace(",", "")) <= 10000 else Staffing.objects.get(station='院长').post_personnel.all().first() if 10000 < float(Subject_obj.total_money.replace(",", "")) <= 200000 else Staffing.objects.get(station='书记').post_personnel.all().first()
                ResearchFundingRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=Subject_obj)

                six_setp = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                ResearchFundingRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=Subject_obj)
                Subject_obj.save()

            elif state == "five":
                if Subject_obj.state in ["one", "two", "three", "four"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Subject_obj.researchfundingrecord_set.filter(node__in=["five", "six"]).delete()
                ResearchFundingRecord.objects.create(parent_id=Subject_obj, audit_people=audit_people_objs.first(), node='five', state='unaudit', audit_note='')
                Subject_obj.current_audit_users.clear()
                Subject_obj.state = 'five'
                Subject_obj.save()
                Subject_obj.current_audit_users.add(audit_people_objs.first())

                six_setp = Staffing.objects.get(station='财务支付').post_personnel.all().first()
                ResearchFundingRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=Subject_obj)
                Subject_obj.save()

            else:
                if Subject_obj.state in ["one", "two", "three", "four", "five"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Subject_obj.researchfundingrecord_set.filter(node__in=["six"]).delete()
                ResearchFundingRecord.objects.create(parent_id=Subject_obj, audit_people=audit_people_objs.first(), node='six', state='unaudit', audit_note='')
                Subject_obj.current_audit_users.clear()
                Subject_obj.state = 'six'
                Subject_obj.save()
                Subject_obj.current_audit_users.add(audit_people_objs.first())

                Subject_obj.save()

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ServiceRequestList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/ServiceRequestList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = PurchasingRequisition.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), state__in=['one', 'two', 'three', 'four', 'six', 'seven', 'stop']).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'ApplicationReason': obj.ApplicationReason,
             'ApplicationType': obj.ApplicationType, 'BudgetAmount': obj.BudgetAmount, 'state': obj.get_state_str(),
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ServiceRequestDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = PurchasingRequisition.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.purchasingrequisitionrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.purchasingrequisitionrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'realname': request.user.real_name, 'position': request.user.post, "is_edit": 'true',
                   'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic,  "flow_dict": flow_dict
                   }
        return render(request, "back_management/ServiceRequestDetail.html", context)

    def post(self, request):
        PurchaId = request.POST.get('SubjectId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Purcha_obj = PurchasingRequisition.objects.get(id=PurchaId)
        if types == 'delete':
            Purcha_obj.purchasingrequisitionrecord_set.all().delete()  # 清除审批列表
            Purcha_obj.current_audit_users.clear()  # 清除当前审批
            Purcha_obj.audit_users_already.clear()  # 清除已审批列表
            Purcha_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人

            if state != 'six' and not audit_people_objs:
                returnDict = {'message': '请选择审批人！', "code": 400}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            if state == "one" or state == 'six':
                if not Purcha_obj.purchasingrequisitionrecord_set.filter(node="one") and state == "one":
                    returnDict = {'message': '申请人为科室负责人，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Purcha_obj.purchasingrequisitionrecord_set.all().delete()
                Purcha_obj.current_audit_users.clear()
                Purcha_obj.audit_users_already.clear()
                flag = True
                if state == 'six':
                    one_appave = Purcha_obj.apply_user.company.head_people
                    if Purcha_obj.apply_user != one_appave:
                        PurchasingRequisitionRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, purchasing_requisition_id=Purcha_obj)
                        flag = False
                        Purcha_obj.state = "six"
                        Purcha_obj.current_audit_users.add(one_appave)

                else:
                    PurchasingRequisitionRecord.objects.create(node='one', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Purcha_obj, audit_note='')
                    flag = False
                    Purcha_obj.state = 'one'
                    Purcha_obj.current_audit_users.add(audit_people_objs.first())

                two_appave = Purcha_obj.apply_user.company.leaders_id
                PurchasingRequisitionRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, purchasing_requisition_id=Purcha_obj)
                if flag:
                    Purcha_obj.state = "two"
                    Purcha_obj.current_audit_users.add(two_appave)

                three_appave = Company.objects.get(id=27).head_people
                PurchasingRequisitionRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, purchasing_requisition_id=Purcha_obj)

                four_appave = Company.objects.get(id=27).leaders_id
                PurchasingRequisitionRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=Purcha_obj)
                Purcha_obj.save()

            elif state == "two":
                if Purcha_obj.state in ["one"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Purcha_obj.purchasingrequisitionrecord_set.filter(node__in=["two", "three", "four"]).delete()
                PurchasingRequisitionRecord.objects.create(node='two', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Purcha_obj)
                Purcha_obj.current_audit_users.clear()
                Purcha_obj.state = 'two'
                Purcha_obj.save()
                Purcha_obj.current_audit_users.add(audit_people_objs.first())

                three_appave = Company.objects.get(id=27).head_people
                PurchasingRequisitionRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, purchasing_requisition_id=Purcha_obj)

                four_appave = Company.objects.get(id=27).leaders_id
                PurchasingRequisitionRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=Purcha_obj)
                Purcha_obj.save()

            elif state == "three":
                if Purcha_obj.state in ["one", "two"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Purcha_obj.purchasingrequisitionrecord_set.filter(node__in=["three", "four"]).delete()
                PurchasingRequisitionRecord.objects.create(node='three', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Purcha_obj)
                Purcha_obj.current_audit_users.clear()
                Purcha_obj.state = 'three'
                Purcha_obj.save()
                Purcha_obj.current_audit_users.add(audit_people_objs.first())

                four_appave = audit_people_objs.first().company.leaders_id
                PurchasingRequisitionRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=Purcha_obj)
                Purcha_obj.save()


            else:
                if Purcha_obj.state in ["one", "two", "three"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Purcha_obj.purchasingrequisitionrecord_set.filter(node__in=["four"]).delete()
                PurchasingRequisitionRecord.objects.create(node='four', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Purcha_obj)
                Purcha_obj.current_audit_users.clear()
                Purcha_obj.state = 'four'
                Purcha_obj.save()
                Purcha_obj.current_audit_users.add(audit_people_objs.first())

                Purcha_obj.save()

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MaterialProcurementList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/MaterialProcurementList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = GoodsProcure.objects.filter(
            Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), state__in=['one', 'two', 'three', 'four', 'six', 'seven', 'stop']).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'PurchaseReason': obj.PurchaseReason,
             'ApplicationType': "紧急" if obj.ApplicationType == '1' else "非紧急", 'GoodsName': obj.GoodsName,
             'custom_made_value': "是" if obj.custom_made_value == '1' else "否", 'BudgetAmount': obj.BudgetAmount,
             'state': obj.get_state_str(),
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()])} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MaterialProcurementDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = GoodsProcure.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.goodsprocurerecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.goodsprocurerecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic,
                   "is_edit": "true", "flow_dict": flow_dict
                   }
        return render(request, "back_management/MaterialProcurementDetail.html", context)

    def post(self, request):
        GoodsId = request.POST.get('SubjectId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Goods_obj = GoodsProcure.objects.get(id=GoodsId)
        if types == 'delete':
            Goods_obj.goodsprocurerecord_set.all().delete()  # 清除审批列表
            Goods_obj.current_audit_users.clear()  # 清除当前审批
            Goods_obj.audit_users_already.clear()  # 清除已审批列表
            Goods_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人
            print(state)
            if state != 'six' and not audit_people_objs:
                returnDict = {'message': '请选择审批人！', "code": 400}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            if state == "one" or state == 'six':
                if not Goods_obj.goodsprocurerecord_set.filter(node="one") and state == "one":
                    returnDict = {'message': '申请人为科室负责人，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Goods_obj.goodsprocurerecord_set.all().delete()
                Goods_obj.current_audit_users.clear()
                Goods_obj.audit_users_already.clear()
                flag = True
                if state == 'six':
                    one_appave = Goods_obj.apply_user.company.head_people
                    if Goods_obj.apply_user != one_appave:
                        GoodsProcureRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, purchasing_requisition_id=Goods_obj)
                        flag = False
                        Goods_obj.state = "six"
                        Goods_obj.current_audit_users.add(one_appave)

                else:
                    GoodsProcureRecord.objects.create(node='one', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Goods_obj, audit_note='')
                    flag = False
                    Goods_obj.state = 'one'
                    Goods_obj.current_audit_users.add(audit_people_objs.first())

                two_appave = Goods_obj.apply_user.company.leaders_id
                GoodsProcureRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, purchasing_requisition_id=Goods_obj)
                if flag:
                    Goods_obj.state = "two"
                    Goods_obj.current_audit_users.add(two_appave)

                three_appave = Company.objects.get(id=27).head_people
                GoodsProcureRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, purchasing_requisition_id=Goods_obj)

                four_appave = Company.objects.get(id=27).leaders_id
                GoodsProcureRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=Goods_obj)
                Goods_obj.save()

            elif state == "two":
                if Goods_obj.state in ["one"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Goods_obj.goodsprocurerecord_set.filter(node__in=["two", "three", "four"]).delete()
                GoodsProcureRecord.objects.create(node='two', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Goods_obj)
                Goods_obj.current_audit_users.clear()
                Goods_obj.state = 'two'
                Goods_obj.save()
                Goods_obj.current_audit_users.add(audit_people_objs.first())

                three_appave = Company.objects.get(id=27).head_people
                GoodsProcureRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, purchasing_requisition_id=Goods_obj)

                four_appave = Company.objects.get(id=27).leaders_id
                GoodsProcureRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=Goods_obj)
                Goods_obj.save()

            elif state == "three":
                if Goods_obj.state in ["one", "two"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Goods_obj.goodsprocurerecord_set.filter(node__in=["three", "four"]).delete()
                GoodsProcureRecord.objects.create(node='three', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Goods_obj)
                Goods_obj.current_audit_users.clear()
                Goods_obj.state = 'three'
                Goods_obj.save()
                Goods_obj.current_audit_users.add(audit_people_objs.first())

                four_appave = audit_people_objs.first().company.leaders_id
                GoodsProcureRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=Goods_obj)
                Goods_obj.save()

            else:
                if Goods_obj.state in ["one", "two", "three"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Goods_obj.goodsprocurerecord_set.filter(node__in=["four"]).delete()
                GoodsProcureRecord.objects.create(node='four', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Goods_obj)
                Goods_obj.current_audit_users.clear()
                Goods_obj.state = 'four'
                Goods_obj.save()
                Goods_obj.current_audit_users.add(audit_people_objs.first())

                Goods_obj.save()

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class RepairReformList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/RepairReformList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = MaintenanceRenovation.objects.filter(
            Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), state__in=['one', 'two', 'three', 'four', 'six', 'seven', 'stop']).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'EntryName': obj.EntryName,
             'ApplicationReason': obj.ApplicationReason, 'CostEstimating': obj.CostEstimating,
             'state': obj.get_state_str(),
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()])} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class RepairReformDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = MaintenanceRenovation.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.maintenancerenovationrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.maintenancerenovationrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic, "is_edit": "true", "flow_dict": flow_dict
                   }
        return render(request, 'back_management/RepairReformDetail.html', context)

    def post(self, request):
        MaintenanceId = request.POST.get('SubjectId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Maintenance_obj = MaintenanceRenovation.objects.get(id=MaintenanceId)
        if types == 'delete':
            Maintenance_obj.maintenancerenovationrecord_set.all().delete()  # 清除审批列表
            Maintenance_obj.current_audit_users.clear()  # 清除当前审批
            Maintenance_obj.audit_users_already.clear()  # 清除已审批列表
            Maintenance_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人
            print(state)
            if state != 'six' and not audit_people_objs:
                returnDict = {'message': '请选择审批人！', "code": 400}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            if state == "one" or state == 'six':
                if not Maintenance_obj.maintenancerenovationrecord_set.filter(node="one") and state == "one":
                    returnDict = {'message': '申请人为科室负责人，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Maintenance_obj.maintenancerenovationrecord_set.all().delete()
                Maintenance_obj.current_audit_users.clear()
                Maintenance_obj.audit_users_already.clear()
                flag = True
                if state == 'six':
                    one_appave = Maintenance_obj.apply_user.company.head_people
                    if Maintenance_obj.apply_user != one_appave:
                        MaintenanceRenovationRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, purchasing_requisition_id=Maintenance_obj)
                        flag = False
                        Maintenance_obj.state = "six"
                        Maintenance_obj.current_audit_users.add(one_appave)

                else:
                    MaintenanceRenovationRecord.objects.create(node='one', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Maintenance_obj, audit_note='')
                    flag = False
                    Maintenance_obj.state = 'one'
                    Maintenance_obj.current_audit_users.add(audit_people_objs.first())

                two_appave = Maintenance_obj.apply_user.company.leaders_id
                MaintenanceRenovationRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, purchasing_requisition_id=Maintenance_obj)
                if flag:
                    Maintenance_obj.state = "two"
                    Maintenance_obj.current_audit_users.add(two_appave)

                three_appave = Company.objects.get(id=27).head_people
                MaintenanceRenovationRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, purchasing_requisition_id=Maintenance_obj)

                four_appave = Company.objects.get(id=27).leaders_id
                MaintenanceRenovationRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=Maintenance_obj)
                Maintenance_obj.save()

            elif state == "two":
                if Maintenance_obj.state in ["one"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Maintenance_obj.maintenancerenovationrecord_set.filter(node__in=["two", "three", "four"]).delete()
                MaintenanceRenovationRecord.objects.create(node='two', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Maintenance_obj)
                Maintenance_obj.current_audit_users.clear()
                Maintenance_obj.state = 'two'
                Maintenance_obj.save()
                Maintenance_obj.current_audit_users.add(audit_people_objs.first())

                three_appave = Company.objects.get(id=27).head_people
                MaintenanceRenovationRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, purchasing_requisition_id=Maintenance_obj)

                four_appave = Company.objects.get(id=27).leaders_id
                MaintenanceRenovationRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=Maintenance_obj)
                Maintenance_obj.save()

            elif state == "three":
                if Maintenance_obj.state in ["one", "two"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Maintenance_obj.maintenancerenovationrecord_set.filter(node__in=["three", "four"]).delete()
                MaintenanceRenovationRecord.objects.create(node='three', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Maintenance_obj)
                Maintenance_obj.current_audit_users.clear()
                Maintenance_obj.state = 'three'
                Maintenance_obj.save()
                Maintenance_obj.current_audit_users.add(audit_people_objs.first())

                four_appave = audit_people_objs.first().company.leaders_id
                MaintenanceRenovationRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=Maintenance_obj)
                Maintenance_obj.save()

            else:
                if Maintenance_obj.state in ["one", "two", "three"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Maintenance_obj.maintenancerenovationrecord_set.filter(node__in=["four"]).delete()
                MaintenanceRenovationRecord.objects.create(node='four', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Maintenance_obj)
                Maintenance_obj.current_audit_users.clear()
                Maintenance_obj.state = 'four'
                Maintenance_obj.save()
                Maintenance_obj.current_audit_users.add(audit_people_objs.first())

                Maintenance_obj.save()

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ComputerRelatedList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/ComputerRelatedList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = ComputerDevice.objects.filter(
            Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), state__in=['one', 'two', 'three', 'four', 'six', 'seven', 'stop']).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'ApplicationReason': obj.ApplicationReason, 'state': obj.get_state_str(),
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()])} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ComputerRelatedDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ComputerDevice.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.computerdevicerecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.computerdevicerecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic,
                   "is_edit": "true", "flow_dict": flow_dict, "ApplicationDetail": json.loads(obj.ApplicationDetail)
                   }
        return render(request, 'back_management/ComputerRelatedDetail.html', context)

    def post(self, request):
        ComputerId = request.POST.get('SubjectId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Computer_obj = ComputerDevice.objects.get(id=ComputerId)
        if types == 'delete':
            Computer_obj.computerdevicerecord_set.all().delete()  # 清除审批列表
            Computer_obj.current_audit_users.clear()  # 清除当前审批
            Computer_obj.audit_users_already.clear()  # 清除已审批列表
            Computer_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人
            if state != 'six' and not audit_people_objs:
                returnDict = {'message': '请选择审批人！', "code": 400}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            if state == "one" or state == 'six':
                if not Computer_obj.computerdevicerecord_set.filter(node="one") and state == "one":
                    returnDict = {'message': '申请人为科室负责人，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Computer_obj.computerdevicerecord_set.all().delete()
                Computer_obj.current_audit_users.clear()
                Computer_obj.audit_users_already.clear()
                flag = True
                if state == 'six':
                    one_appave = Computer_obj.apply_user.company.head_people
                    if Computer_obj.apply_user != one_appave:
                        ComputerDeviceRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, purchasing_requisition_id=Computer_obj)
                        flag = False
                        Computer_obj.state = "six"
                        Computer_obj.current_audit_users.add(one_appave)

                else:
                    ComputerDeviceRecord.objects.create(node='one', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Computer_obj, audit_note='')
                    flag = False
                    Computer_obj.state = 'one'
                    Computer_obj.current_audit_users.add(audit_people_objs.first())

                two_appave = Company.objects.get(id=31).head_people
                ComputerDeviceRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, purchasing_requisition_id=Computer_obj)
                if flag:
                    Computer_obj.state = "two"
                    Computer_obj.current_audit_users.add(two_appave)

                three_appave = Computer_obj.apply_user.company.leaders_id
                ComputerDeviceRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, purchasing_requisition_id=Computer_obj)

                four_appave = Company.objects.get(id=23).leaders_id
                ComputerDeviceRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=Computer_obj)
                Computer_obj.save()

            elif state == "two":
                if Computer_obj.state in ["one"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Computer_obj.computerdevicerecord_set.filter(node__in=["two", "three", "four"]).delete()
                ComputerDeviceRecord.objects.create(node='two', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Computer_obj)
                Computer_obj.current_audit_users.clear()
                Computer_obj.state = 'two'
                Computer_obj.save()
                Computer_obj.current_audit_users.add(audit_people_objs.first())

                three_appave = Computer_obj.apply_user.company.leaders_id
                ComputerDeviceRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, purchasing_requisition_id=Computer_obj)

                four_appave = Company.objects.get(id=23).leaders_id
                ComputerDeviceRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=Computer_obj)
                Computer_obj.save()

            elif state == "three":
                if Computer_obj.state in ["one", "two"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Computer_obj.computerdevicerecord_set.filter(node__in=["three", "four"]).delete()
                ComputerDeviceRecord.objects.create(node='three', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Computer_obj)
                Computer_obj.current_audit_users.clear()
                Computer_obj.state = 'three'
                Computer_obj.save()
                Computer_obj.current_audit_users.add(audit_people_objs.first())

                four_appave = Company.objects.get(id=23).leaders_id
                ComputerDeviceRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, purchasing_requisition_id=Computer_obj)
                Computer_obj.save()

            else:
                if Computer_obj.state in ["one", "two", "three"]:
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Computer_obj.computerdevicerecord_set.filter(node__in=["four"]).delete()
                ComputerDeviceRecord.objects.create(node='four', state='unaudit', audit_people=audit_people_objs.first(), purchasing_requisition_id=Computer_obj)
                Computer_obj.current_audit_users.clear()
                Computer_obj.state = 'four'
                Computer_obj.save()
                Computer_obj.current_audit_users.add(audit_people_objs.first())

                Computer_obj.save()

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ProjectAuditList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/ProjectAuditList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_data", '')  # 查询标题
        objs = ObjectAudit.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), state__in=['one', 'two', 'eight', 'seven', 'stop']).order_by('-create_time')

        data_list = [{'id': obj.id, 'apply_user': obj.apply_user.real_name, 'company': obj.company.name, 'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]), 'state': obj.get_state_str(), "title": obj.work_name}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ProjectAuditDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ObjectAudit.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.objectauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.objectauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                              'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3], "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true', 'is_stop': 'true' if obj.state in ['one', 'two'] and request.user == obj.apply_user else 'false', 'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace( "\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'back_management/ProjectAuditDetail.html', context)

    def post(self, request):
        ObjectId = request.POST.get('SubjectId', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Object_obj = ObjectAudit.objects.get(id=ObjectId)
        if types == 'delete':
            Object_obj.objectauditrecord_set.all().delete()  # 清除审批列表
            Object_obj.current_audit_users.clear()  # 清除当前审批
            Object_obj.audit_users_already.clear()  # 清除已审批列表
            Object_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人
            if state != 'six' and not audit_people_objs:
                returnDict = {'message': '请选择审批人！', "code": 400}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            if state == "one" or state == 'eight':
                if not Object_obj.objectauditrecord_set.filter(node="one") and state == "one":
                    returnDict = {'message': '申请人为科室负责人，无法退回该节点！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Object_obj.objectauditrecord_set.all().delete()
                Object_obj.current_audit_users.clear()
                Object_obj.audit_users_already.clear()

                OneStep = Object_obj.company.head_people
                ObjectAuditRecord.objects.create(node="two", state='unaudit', audit_people=Object_obj.company.leaders_id, parent_id=Object_obj, audit_note='')
                if state == "one":
                    Object_obj.state = 'one'
                    ObjectAuditRecord.objects.create(node="one", state='unaudit', audit_people=audit_people_objs.first(), parent_id=Object_obj, audit_note='')
                    Object_obj.current_audit_users.add(audit_people_objs.first())

                else:
                    Object_obj.state = 'eight'
                    Object_obj.current_audit_users.add(Object_obj.apply_user)
                    if Object_obj.apply_user != OneStep:
                        ObjectAuditRecord.objects.create(node="one", state='unaudit', audit_people=OneStep, parent_id=Object_obj, audit_note='')

                ObjectAuditRecord.objects.create(node="two", state='unaudit', audit_people=Object_obj.company.leaders_id, parent_id=Object_obj, audit_note='')
                Object_obj.save()

            else:
                if Object_obj.state == "one":
                    returnDict = {'message': '流程退回只能退回至当前节点之前！', "code": 400}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                Object_obj.objectauditrecord_set.filter(node__in=["two"]).delete()
                ObjectAuditRecord.objects.create(node='two', state='unaudit', audit_people=audit_people_objs.first(), parent_id=Object_obj, audit_note='')
                Object_obj.current_audit_users.clear()
                Object_obj.state = 'two'
                Object_obj.save()
                Object_obj.current_audit_users.add(audit_people_objs.first())

                Object_obj.save()

            returnDict = {'message': '修改成功！', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ExternalCorrespondenceList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/ExternalCorrespondenceList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_data", '')  # 查询标题
        objs = Correspondence.objects.filter(Q(send_company__contains=search_value) | Q(title__contains=search_value) | Q(send_number__contains=search_value) |
                                                Q(send_company__contains=search_value) | Q(recive_number__contains=search_value) | Q(apply_user__real_name__contains=search_value) |
                                                Q(create_time__contains=search_value)).order_by('-create_time')
        review_list, distributed, return_list, circulation, end_list, cancel_list, stop_list, recall_list = [], [], [], [], [], [], [], []
        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            one_dict = {'id': obj.id, 'Communication': obj.send_company, 'title': obj.title, 'document_font': obj.send_number, 'type': obj.type,
                        'document_no': obj.recive_number, 'recipient': obj.apply_user.real_name, 'status': obj.get_state_str(),
                        'approver': ', '.join([i.real_name for i in obj.current_audit_users.all()]), 'receiving_time': obj.create_time.strftime("%Y-%m-%d %H:%M")}
            if obj.type == "g":
                distributed.append(one_dict)
            elif obj.type == "f":
                return_list.append(one_dict)
            elif obj.type == "e":
                end_list.append(one_dict)
            elif obj.type == "d":
                circulation.append(one_dict)
            elif obj.type == "cancel":
                cancel_list.append(one_dict)
            elif obj.type == "stop":
                stop_list.append(one_dict)
            elif obj.type == "recall":
                recall_list.append(one_dict)
            else:
                review_list.append(one_dict)
        data_list = review_list + return_list + distributed + stop_list + recall_list + cancel_list + circulation + end_list
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ExternalCorrespondenceDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = Correspondence.objects.get(id=int(id))
        approve_flag = ""
        if request.user in obj.current_audit_users.all():
            approve_flag = True
        p_obj = obj.correspondencepeople_set.filter(audit_people=request.user, state='accept').first()
        if p_obj:
            p_obj.state = 'accepted'
            p_obj.update_time = datetime.now()
            p_obj.save()

        if obj.correspondencepeople_set.filter(state='accept').count() == 0 and obj.type == 'd':
            obj.type = 'five'
            obj.save()

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", '/'),
                      "pdf_path": atta_obj.pdf_path.replace("\\", '/'),
                      "file_size": atta_obj.file_size,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      'word_path': os.getcwd() + "/media/" + str(atta_obj.file_path).replace("\\", '/'),
                      "uploader": atta_obj.uploader_user.real_name, "id": atta_obj.id,
                      "topics_number": atta_obj.topics_number} for atta_obj in
                     Topicsattachments.objects.filter(topics_number=obj.uuid, file_type="0")]

        file_list1 = [{"file_name": atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", '/')} for atta_obj in
                      Topicsattachments.objects.filter(topics_number=obj.uuid, file_type="1")]

        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.correspondencerecord_set.filter(~Q(node='eight')):
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        appave_count = obj.correspondencerecord_set.filter(~Q(node='eight')).values("audit_people").distinct().count()

        recive_people, no_recive, recive = [], [], []
        for record in obj.correspondencepeople_set.all():
            one_dict = {'user': record.audit_people.real_name, 'state': record.get_state_display(),
                          'signature_picture': '/media/' + str(record.audit_people.signature_picture) if (record.audit_people.signature_picture and record.state == 'accepted') else '',
                          'update_time': record.update_time.strftime("%Y-%m-%d %H:%M") if record.state == 'accepted' else ''}
            recive_people.append(one_dict)
            if record.state == 'accept':
                no_recive.append(one_dict)
            else:
                recive.append(one_dict)

        staff_obj = Staffing.objects.filter(station="办公室")

        flag = 0
        if staff_obj:
            for tt in staff_obj:
                personnel = tt.post_personnel.all()
                for jj in personnel:
                    if jj == request.user:
                        flag = 1

        data_dic = {
            'id': obj.id, 'appave_count': appave_count, 'yes_count': len(recive), 'recive': recive,
            'node': obj.get_type_display(), 'no_count': len(no_recive), 'no_recive': no_recive,
            'type': obj.type, 'all_count': len(recive_people), 'recive_people': recive_people,
            'apply_user': obj.apply_user.real_name, 'department': obj.apply_user.department, 'send_number': obj.send_number,
            'recive_number': obj.recive_number, 'title': obj.title, "uuid": obj.uuid, 'send_company': obj.send_company, 'content': obj.content,
            'annotated_text': obj.annotated_text, 'time_limit': obj.time_limit, 'remarks': obj.remarks, 'file_list': file_list,
            'flag': flag, 'fenfa_flag': 'true' if obj.type == 'eight' and request.user == obj.apply_user else 'flase', 'file_list1': file_list1,
            'recive_time': obj.recive_time.strftime("%Y-%m-%d %H:%M"), 'revocation_flag' : 'true',  # 撤回标签，’true‘ 有该权限
            'file_path': Topicsattachments.objects.filter(topics_number=obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.uuid) else "",
            'is_stop': 'true' if obj.type in ['one', 'two', 'three', 'four', 'six', 'seven', 'eight'] and request.user == obj.apply_user else 'false',
        }
        returnDict = {'realname': real_name, 'position': position, 'department': department, 'data_dic': data_dic, "audit_dic": audit_dic, "approve_flag": approve_flag}
        return render(request, "back_management/ExternalCorrespondenceDetail.html", returnDict)

    def post(self, request):
        ObjectId = request.POST.get('id', None)  # 用印流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Object_obj = Correspondence.objects.get(id=ObjectId)
        if types == 'delete':
            Object_obj.correspondencerecord_set.all().delete()  # 清除审批列表
            Object_obj.current_audit_users.clear()  # 清除当前审批
            Object_obj.audit_users_already.clear()  # 清除已审批列表
            Object_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人
            if state == 'one':
                Object_obj.correspondencepeople_set.all().delete()
                Object_obj.correspondencerecord_set.all().delete()
                Object_obj.current_audit_users.clear()
                for audit_people_obj in audit_people_objs:
                    CorrespondenceRecord.objects.create(official_documents_id=Object_obj, state='unaudit', audit_people=audit_people_obj, audit_note='', node='one')
                    Object_obj.current_audit_users.add(audit_people_obj)
                Object_obj.type = state
                Object_obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            elif state == 'two':
                if Object_obj.type == 'one':
                    returnData = {'code': 500, 'message': '该流程未到达该节点！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                Object_obj.correspondencepeople_set.all().delete()
                Object_obj.correspondencerecord_set.filter(node__in=['two', 'three', "eight"]).delete()
                Object_obj.current_audit_users.clear()
                for audit_people_obj in audit_people_objs:
                    CorrespondenceRecord.objects.create(official_documents_id=Object_obj, state='unaudit', audit_people=audit_people_obj, audit_note='', node='two')
                    Object_obj.current_audit_users.add(audit_people_obj)

                Object_obj.type = state
                Object_obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            elif state == 'three':
                if Object_obj.type in ['one', 'two']:
                    returnData = {'code': 500, 'message': '该流程未到达该节点！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                Object_obj.correspondencepeople_set.all().delete()
                Object_obj.correspondencerecord_set.filter(node='three').delete()
                Object_obj.current_audit_users.clear()
                for audit_people_obj in audit_people_objs:
                    CorrespondenceRecord.objects.create(official_documents_id=Object_obj, state='unaudit', audit_people=audit_people_obj, audit_note='', node='three')
                    Object_obj.current_audit_users.add(audit_people_obj)
                Object_obj.type = state
                Object_obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            elif state == 'six':
                Object_obj.correspondencepeople_set.all().delete()
                Object_obj.correspondencerecord_set.all().delete()
                Object_obj.current_audit_users.clear()
                dzb_obj = Company.objects.get(id=3)
                dzb_director = dzb_obj.head_people
                CorrespondenceRecord.objects.create(official_documents_id=Object_obj, state='unaudit', node='one', audit_note='', audit_people=dzb_director)
                Object_obj.current_audit_users.add(Object_obj.apply_user)
                Object_obj.type = state
                Object_obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            elif state == 'eight':
                Object_obj.correspondencepeople_set.all().delete()
                Object_obj.correspondencerecord_set.filter(node__in=['three', "eight"]).delete()
                CorrespondenceRecord.objects.create(official_documents_id=Object_obj, audit_people=Object_obj.apply_user, audit_note='', node='eight')
                Object_obj.current_audit_users.add(Object_obj.apply_user)
                Object_obj.type = state
                Object_obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            else:
                returnData = {'code': 500, 'message': '请选择正确的状态！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

class InitiateVoting(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/InitiateVoting.html")

    def post(self, request):
        apply_user = request.POST.get("apply_user", None)
        vote_title = request.POST.get("vote_title", None)            # 投票标题
        vote_content = request.POST.get("vote_content", None)  # 投票详情
        VatTextList = request.POST.get("VatTextList", None)     # 投票选项
        vote_type = request.POST.get("vote_type", None)          # 投票类型
        vote_deadline = request.POST.get("vote_deadline", None)  # 投票截至时间
        VotingOption = request.POST.get("VotingOption", None)   # 可投票人
        vote_viewable = request.POST.get("vote_viewable", None)   # 投票结果可查看类型

        apply_user_number = re.findall('\((.*?)\)', apply_user)

        obj = VotingMasterTable.objects.create(
            apply_user=User.objects.get(job_number=apply_user_number[0]), vote_title=vote_title, vote_content=vote_content, vote_type=vote_type, vote_deadline=vote_deadline, vote_viewable=vote_viewable
        )

        vat_text_list = json.loads(VatTextList)
        for j in vat_text_list:
            VotingOptionTable.objects.create(voting_id=obj, option=j)

        VotingOptionList = json.loads(VotingOption)
        if len(VotingOptionList):
            for i in VotingOptionList:
                voting_people_number = re.findall('\((.*?)\)', i)
                VotingPeopleTable.objects.create(voting_id=obj, apply_user=User.objects.get(job_number=voting_people_number[0]))
        else:
            all_user_list = User.objects.filter(is_delete=0)
            for users in all_user_list:
                VotingPeopleTable.objects.create(voting_id=obj, apply_user=users)

        returnData = {'code': 200, 'message': '创建成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class VoteList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/VoteList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_data", '')  # 查询标题
        objs = VotingMasterTable.objects.filter( Q(vote_title__contains=search_value) | Q(apply_user__real_name__contains=search_value)).order_by('-create_time')
        data_list = []
        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            now_timestamp = int(time.time())
            end_timestamp = int(str_to_timestamp(obj.vote_deadline, '%Y-%m-%d'))
            if (now_timestamp - end_timestamp) > 0:
                state = "结束"
                obj.state = "ending"
                obj.save()
            else:
                state = "投票中" if obj.state == 'voting' else "结束"
            data_list.append(
                {'id': obj.id, 'create_time': obj.create_time.strftime("%Y-%m-%d"), 'vote_title': obj.vote_title, 'vote_deadline': obj.vote_deadline, "apply_user": obj.apply_user.real_name,
                 'vote_viewable': "投票者可见" if obj.vote_viewable == 'one' else "发起者可见", 'state': state, "vote_number": obj.votingpeopletable_set.all().count(),
                 'rlread_number':obj.votingpeopletable_set.filter(voting_option__isnull=False).count()}
            )
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class BiddingProcurementProjectList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/BiddingProcurementProjectList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = BiddingProcurementProject.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), state__in=['one', 'two', 'three', 'four', 'five', 'eight', 'seven', 'stop']).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'create_time': obj.create_time.strftime("%Y-%m-%d"), 'company': obj.company.name, 'categories': '工程类' if obj.categories == '1' else '货物类' if obj.categories == '2' else '服务类',
             'ApplicationReason': obj.ApplicationReason, 'budget_amount': obj.budget_amount, 'project_leader': obj.project_leader, 'state': obj.get_state_str(), 'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class BiddingProcurementProjectDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = BiddingProcurementProject.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.biddingprocurementprojectrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.biddingprocurementprojectrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note,
                     'audit_time': audit_obj.update_time.strftime(
                         "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                 audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                          os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list, 'is_edit': 'true',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'eight'] and request.user == obj.apply_user else 'false',
                   'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, "back_management/BiddingProcurementProjectDetail.html", context)

    def post(self, request):
        ObjectId = request.POST.get('id', None)  # 流程ID
        types = request.POST.get("type", None)  # 操作类型：delete，删除
        Object_obj = BiddingProcurementProject.objects.get(id=ObjectId)
        if types == 'delete':
            Object_obj.biddingprocurementprojectrecord_set.all().delete()  # 清除审批列表
            Object_obj.current_audit_users.clear()  # 清除当前审批
            Object_obj.audit_users_already.clear()  # 清除已审批列表
            Object_obj.delete()
            returnDict = {'status': 'success', "code": 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            state = request.POST.get("state", None)  # 退回的节点
            audit_people = request.POST.get("audit_people", None)
            audit_people_list = re.findall('\((.*?)\)', audit_people)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)  # 审批人
            if state == 'one':
                Object_obj.biddingprocurementprojectrecord_set.all().delete()
                Object_obj.current_audit_users.clear()
                for audit_people_obj in audit_people_objs:
                    BiddingProcurementProjectRecord.objects.create(parent_id=Object_obj, state='unaudit', audit_people=audit_people_obj, audit_note='', node='one')
                    Object_obj.current_audit_users.add(audit_people_obj)
                Object_obj.state = state
                Object_obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            elif state == 'two':
                if Object_obj.state == 'one':
                    returnData = {'code': 500, 'message': '该流程未到达该节点！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                Object_obj.biddingprocurementprojectrecord_set.filter(node__in=['two', 'three', "four", "five"]).delete()
                Object_obj.current_audit_users.clear()
                for audit_people_obj in audit_people_objs:
                    BiddingProcurementProjectRecord.objects.create(parent_id=Object_obj, state='unaudit', audit_people=audit_people_obj, audit_note='', node='two')
                    Object_obj.current_audit_users.add(audit_people_obj)

                Object_obj.state = state
                Object_obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            elif state == 'three':
                if Object_obj.state in ['one', 'two']:
                    returnData = {'code': 500, 'message': '该流程未到达该节点！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                Object_obj.biddingprocurementprojectrecord_set.filter(node__in=['three', "four", "five"]).delete()
                Object_obj.current_audit_users.clear()
                for audit_people_obj in audit_people_objs:
                    BiddingProcurementProjectRecord.objects.create(parent_id=Object_obj, state='unaudit', audit_people=audit_people_obj, audit_note='', node='three')
                    Object_obj.current_audit_users.add(audit_people_obj)
                Object_obj.state = state
                Object_obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            elif state == 'four':
                if Object_obj.state in ['one', 'two', 'three']:
                    returnData = {'code': 500, 'message': '该流程未到达该节点！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                Object_obj.biddingprocurementprojectrecord_set.filter(node__in=["four", "five"]).delete()
                Object_obj.current_audit_users.clear()
                for audit_people_obj in audit_people_objs:
                    BiddingProcurementProjectRecord.objects.create(parent_id=Object_obj, state='unaudit', audit_people=audit_people_obj, audit_note='', node='four')
                    Object_obj.current_audit_users.add(audit_people_obj)
                Object_obj.state = state
                Object_obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            elif state == 'five':
                if Object_obj.state in ['one', 'two', 'three', 'four']:
                    returnData = {'code': 500, 'message': '该流程未到达该节点！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                Object_obj.biddingprocurementprojectrecord_set.filter(node__in=["five"]).delete()
                Object_obj.current_audit_users.clear()
                for audit_people_obj in audit_people_objs:
                    BiddingProcurementProjectRecord.objects.create(parent_id=Object_obj, state='unaudit', audit_people=audit_people_obj, audit_note='', node='five')
                    Object_obj.current_audit_users.add(audit_people_obj)
                Object_obj.state = state
                Object_obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            elif state == 'eight':
                Object_obj.biddingprocurementprojectrecord_set.all().delete()
                Object_obj.current_audit_users.add(Object_obj.apply_user)

                one_appave =Object_obj.company.head_people
                if Object_obj.apply_user != one_appave:
                    BiddingProcurementProjectRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, parent_id=Object_obj)

                two_appave = Object_obj.company.leaders_id
                BiddingProcurementProjectRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, parent_id=Object_obj)

                three_appave = Company.objects.get(id=9).head_people
                BiddingProcurementProjectRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, parent_id=Object_obj)

                four_appave = Company.objects.get(id=9).leaders_id
                BiddingProcurementProjectRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, parent_id=Object_obj)

                Object_obj.state = state
                Object_obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            else:
                returnData = {'code': 500, 'message': '请选择正确的状态！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

class QuestionnaireSurvey(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/QuestionnaireSurvey.html")

    def post(self, request):
        survey_title = request.POST.get("survey_title", '')
        apply_user = request.POST.get("apply_user", '')
        start_time = request.POST.get("start_time", '')
        end_time = request.POST.get("end_time", '')
        illustrate = request.POST.get("illustrate", '')
        survey_list = json.loads(request.POST.get("survey_list", ''))
        VotingOption = json.loads(request.POST.get("VotingOption", ''))

        promoter = re.findall('\((.*?)\)', apply_user)
        main_obj = QuestionnaireTable.objects.create(
            apply_user=User.objects.get(job_number=promoter[0]), title=survey_title, illustrate=illustrate, start_time=start_time, end_time=end_time
        )

        for i in survey_list:
            title_obj = QuestionnaireTitle.objects.create(survey_id=main_obj, survey_title=i["title"], option_type=i["type"])
            for j in i["OptionList"]:
                QuestionnaireQuestions.objects.create(survey_id=title_obj, option=j.strip())
            for k in VotingOption:
                QuestionnairePeople.objects.create(parent_id=main_obj, survey_id=title_obj, apply_user=User.objects.get(job_number=k.split('(')[1].replace(")", "")))
        returnData = {'code': 200, 'message': '创建完成！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class QuestionnaireRecords(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/QuestionnaireRecords.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)

        search_value = request.POST.get("search_value", '')
        objs = QuestionnaireTable.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(title__contains=search_value)).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'title': obj.title, 'end_time': obj.end_time, 'state': obj.get_state_str()
             } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProcessNodes(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        father_obj = ModuleManagement.objects.all()
        obj_dict = {}
        for father in father_obj:
            obj_dict[father.name] = {}
            son_obj = ModuleManagementChildren.objects.filter(parent_id=father)
            for son in son_obj:
                obj_dict[father.name][son.name] = {"father_abbreviation": father.abbreviation, "son_name": son.name, "son_abbreviation": son.abbreviation, "flow_chart": son.flow_chart, "son_id": son.id}
        return render(request, "back_management/ProcessNodes.html", {"obj": obj_dict})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = ProcessNodesMainTable.objects.all().order_by('-create_time')

        data_list = [{'id': obj.id, 'module': obj.module.name, 'process_name': obj.process_name,
             'process_coding': obj.process_coding, 'people': obj.operator.real_name} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class AddNodes(View):
    def post(self, request):
        module = request.POST.get("module", '')              # 所属模块
        process_name = request.POST.get("process_name", "")  # 流程名称
        abbreviation = request.POST.get("abbreviation", "")  # 流程简称
        process_coding = request.POST.get("process_coding", "")  # 流程编号
        operator = request.POST.get("operator", "")             # 操作人
        table_json = request.POST.get("table_json", "")

        audit_people_list = re.findall('\((.*?)\)', operator)
        people_objs = User.objects.filter(job_number__in=audit_people_list)

        ModuleObj = CustomerFormModule.objects.get(id=int(module.split("-")[0]))
        objs = ProcessNodesMainTable.objects.create(process_name=process_name, process_coding=process_coding, operator=people_objs.first(), module=ModuleObj, abbreviation=abbreviation)

        for i in json.loads(table_json):
            ProcessNodesSecondaryTable.objects.create(parent_id=objs, serial=i[0], nodes=i[1], describe=i[2])

        returnData = {'code': 200, 'message': '添加成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class ExpertLibraryList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/ExpertLibraryList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = ExpertDatabase.objects.all().order_by('-create_time')

        data_list = [{'id': obj.id, 'name': obj.name, 'description': obj.description,
             'people_list': ", ".join([j.name for j in obj.expertpeople_set.all()])} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class UploadExpertRoster(View):
    def get(self, request):
        flow_id = request.GET.get("flow_id", "")
        obj = ExpertDatabase.objects.get(id=int(flow_id))
        obj.expertpeople_set.all().delete()
        obj.delete()
        returnData = {'code': 200, 'message': '删除成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

    def post(self, request):
        files = request.FILES.get('files')
        ExpertName = request.POST.get("ExpertName", "")
        description = request.POST.get("description", "")
        read_file = xlrd.open_workbook(filename=None, file_contents=files.read())
        file_table = read_file.sheets()[0]
        file_table_rows = file_table.nrows
        obj = ExpertDatabase.objects.create(name=ExpertName, description=description)
        for t in range(1, file_table_rows):
            try:
                ExpertPeople.objects.create(name=file_table.cell(t, 0).value, parent_id=obj)
            except:
                returnData = {'code': 400, 'message': '请下载专家库名单重新上传！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '上传成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class CommitteeNameList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/CommitteeNameList.html", {'company_list': [{"id": c.id, "name": c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")]})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)

        search_value = request.POST.get("search_value", '')
        objs = CommitteeTable.objects.filter(Q(committee_name__contains=search_value)).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'company': obj.company.name, 'committee_name': obj.committee_name, 'committee_level': obj.committee_level,
             'liaison_officer': obj.liaison_officer.real_name} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class CommitteeNameSave(View):
    def post(self, request):
        committee_name = request.POST.get("committee_name", "")                             # 委员会名称
        committee_level = request.POST.get("committee_level", "")                       # 委员会级别
        chairman = request.POST.get("chairman", "")
        vice_chairman = request.POST.get("vice_chairman", "")
        liaison_officer = request.POST.get("liaison_officer", "")                           # 联络员
        company = request.POST.get("company", "")
        members = request.POST.get("members", "")

        LiaisonOfficer = re.findall('\((.*?)\)', liaison_officer)
        obj = CommitteeTable.objects.create(committee_name=committee_name, committee_level=committee_level, liaison_officer=User.objects.get(job_number=LiaisonOfficer[0]), company=Company.objects.get(name=company))
        chairman_list = re.findall('\((.*?)\)', chairman)
        for cha in chairman_list:
            obj.chairman.add(User.objects.get(job_number=cha))

        vice_chairman_list = re.findall('\((.*?)\)', vice_chairman)
        for vice in vice_chairman_list:
            obj.vice_chairman.add(User.objects.get(job_number=vice))

        members_list = re.findall('\((.*?)\)', members)
        for mem in members_list:
            print("=================", mem)
            CommitteeTablePeople.objects.create(parent_id=obj, member=User.objects.get(job_number=mem))
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

def generate_verification_code(length):
    code = ''
    for i in range(length):
        code += str(random.randint(0, 9))
    return code

class ApplyCode(View):
    def post(self, request):
        username = request.POST.get("username", "")
        backend_administrator = Staffing.objects.get(station="后端管理员").post_personnel.all()
        current_login_person = User.objects.get(job_number=username)
        if current_login_person not in backend_administrator:
            returnData = {'code': 400, 'message': '非管理员无法登录！', }
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        code = generate_verification_code(6)
        print("==================", code)
        request.session['verification_code'] = code
        request.session['session_time'] = time.time()
        message_str = f"动态验证码为{code}，您正在登录京山市人民医院OA管理端，验证码有效时间为一分钟，请尽快验证。"
        administrators_obj = Staffing.objects.get(station='超级管理员').post_personnel.all().first()
        send_mssage([administrators_obj.mobile], message_str)
        returnData = {'code': 200, 'message': '操作成功！', }
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class PayList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        return render(request, "back_management/PayList.html")

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = PaymentApproval.objects.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'apply_user': obj.apply_user.real_name, 'company': obj.apply_user.company.name,
                      'title': obj.title, 'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      'state': obj.get_state_str(), 'total_money': obj.total_money}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class PayDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = PaymentApproval.objects.get(id=id)
        if obj.topics_id:
            audit_dic = {}
            topics_obj = obj.topics_id
            for audit_obj in topics_obj.topicsauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state, 'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
            main_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "pdf_path": atta_obj.pdf_path,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                     os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in
                Topicsattachments.objects.filter(topics_number=topics_obj.uuid, file_type="0")]
            flow_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "pdf_path": atta_obj.pdf_path, "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                    os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)
            ]
            topic_audit_dic, topic_flow_dict = {}, {}
            for audit_obj in obj.paymentapprovalrecord_set.all():
                if audit_obj.node in topic_audit_dic:
                    topic_audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                            'state_display': audit_obj.get_state_display(),
                                                            'state': audit_obj.state, 'node': audit_obj.node,
                                                            'node_display': audit_obj.get_node_display(),
                                                            'audit_note': audit_obj.audit_note,
                                                            'audit_time': audit_obj.update_time.strftime(
                                                                "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                            'signature_picture': '/media/' + str(
                                                                audit_obj.audit_people.signature_picture) if (
                                                                        audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in obj.paymentapprovalrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    topic_flow_dict[audit_obj.node] = {'apply': apply,
                                                       'apply_people': ','.join(list(set(apply_people))),
                                                       'sear': len([i for i in topic_flow_dict]) + 1}
                    topic_audit_dic[audit_obj.node] = [
                        {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                         'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                         'audit_note': audit_obj.audit_note,
                         'audit_time': audit_obj.update_time.strftime(
                             "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                         'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                     audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            help_department = ' ,'.join([i.name for i in topics_obj.help_department.all()])
            help_department1 = ' ,'.join([f"{i.name}({i.id})" for i in topics_obj.help_department.all()])

            received_audit_dic, company_type = {}, ''
            if topics_obj.received_foreign:
                received_obj = topics_obj.received_foreign
                company_type = "yb" if topics_obj.received_foreign.apply_user.company.id == 80 else "db"
                for audit_obj in received_obj.officialdocumentsauditrecord_set.all():
                    if audit_obj.node in received_audit_dic:
                        received_audit_dic[audit_obj.node].append(
                            {'audit_user': audit_obj.audit_people.real_name,
                             'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                             'node': audit_obj.node,
                             'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                             'audit_time': audit_obj.update_time.strftime(
                                 "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                             'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                         audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                    else:
                        received_audit_dic[audit_obj.node] = [
                            {'audit_user': audit_obj.audit_people.real_name,
                             'state_display': audit_obj.get_state_display(),
                             'state': audit_obj.state, 'node': audit_obj.node,
                             'node_display': audit_obj.get_node_display(),
                             'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime(
                                "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                             'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                         audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            data_dic = {'realname': real_name, 'position': request.user.post, 'department': request.user.company.name,
                        'apply_user': topics_obj.employee.real_name, 'state': topics_obj.get_state_display(),
                        'main_file_list': main_file_list + flow_file_list, 'number': topics_obj.number,
                        'topics_name': topics_obj.topics_name, "flow_file_list": flow_file_list,
                        'topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_text).decode()).decode()),
                        'topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_basis).decode()).decode()),
                        'solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.solution).decode()).decode()) if topics_obj.solution != "空" else "",
                        'db_topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_text).decode()).decode()) if topics_obj.db_topics_text else "",
                        'db_topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_basis).decode()).decode()) if topics_obj.db_topics_basis else "",
                        'db_solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_solution).decode()).decode()) if topics_obj.db_solution else "",
                        'topics_estimate': topics_obj.topics_estimate, 'help_department': help_department, 'help_department1': help_department1,
                        'jfly': topics_obj.jfly if topics_obj.jfly else "", 'ysje': topics_obj.ysje if topics_obj.ysje else "", 'uuid': obj.fj_number,
                        'audit_list': audit_dic, "topic_audit_dic": topic_audit_dic, "topic_flow_dict": topic_flow_dict,
                        "obj": topics_obj, "flow_obj": obj, "is_refer": 'true' if obj.state == 'zero' else 'false',
                        'received_audit_dic': received_audit_dic, 'company_type': company_type,
                        'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                        'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six"] and request.user in obj.current_audit_users.all() else 'false',
                        'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'eight'] and request.user == obj.apply_user else 'false',
                        'file_path': Topicsattachments.objects.filter(topics_number=topics_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=topics_obj.uuid) else ''}
            return render(request, 'back_management/PayDetailTransfer.html', data_dic)
        else:
            audit_dic, flow_dict = {}, {}
            for audit_obj in obj.paymentapprovalrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in obj.paymentapprovalrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                 "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

            bgs_flag = 'true' if request.user.company.id == 80 else 'false'
            leaders_obj = User.objects.filter(group_id__in=[1, 2], is_delete=False)
            returndata = Company.objects.filter(~Q(id=87)).order_by("serial_number")
            company_list, ComList = [], []
            for c in returndata:
                if c.name not in ComList:
                    one_dict = {"id": c.id, "name": c.name}
                    company_list.append(one_dict)
                    ComList.append(c.name)
            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                       "obj": obj, 'audit_dic': audit_dic, "file_list": file_list, "leaders_obj": leaders_obj,
                       "company_list": company_list, 'is_edit': 'false', 'flow_dict': flow_dict, "revise": revise, "bgs_flag": bgs_flag,
                       'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                       }
            return render(request, 'back_management/PayDetail.html', context)
